ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: How To Securing your ASP.NET MVC Application

clock February 7, 2017 05:05 by author Armend

Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one's web application.

By decorating the HomeController using the Authorize attribute (notice I didn't specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

[Authorize]
public class HomeController : Controller
{
  //...
}

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

[Authorize]
public ActionResult Create()
{
  //...
}

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there's security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult Create()
{
  //...
}

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

public ActionResult LogOn()
        {
            return View();
        }
       
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect");
                }
            }

            // if we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

public class LogOnModel
        {
            [Required]
            [Display(Name = "User name")]
            public string UserName { get; set; }
            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }
            [Display(Name = "Remember me?")]
            public string RememberMe { get; set; }
        }

Lastly, add the following to the project’s web.config file:

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPhostPortal.com :: Tips Create User Roles in ASP.NET MVC

clock December 20, 2016 04:54 by author Armend

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more.

In this article, We'll look into how to create default user roles in ASP.NET MVC 5. Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}


What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))
    Roles.CreateRole("Standard");
Roles.AddUserToRole(model.UserName, "Standard");


Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:


@if (Roles.GetRolesForUser().Contains("Admin"))
{
}

 

Best ASP.NET MVC Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

 



ASP.NET Hosting - ASPHostPortal.com :: Tips to Create Create WebGrid with Expand in ASP.NET MVC

clock September 6, 2016 19:53 by author Armend

Introduction

In this post, I am explain How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC 6.
Steps :

Step - 1 : Create New Project.

  • Go to File > New > Project > Select asp.net MVC6 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

  • Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

  • Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > OK.

In this example, I have used two tables as below

Step-4: Add Entity Data Model.

  • Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
  • A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
  • Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a class for create a view model.

  • 1st : Add a folder.
  • Go to Solution Explorer > Right Click on the project > add > new folder.
  • 2nd : Add a class on that folder
  • Go to Solution Explorer > Right Click on that folder > Add > Class... > Enter Class name > Add.

Write the following code in this class

using System.Collections.Generic;
namespace MVCNestedWebgrid.ViewModel
{
    public class OrderVM
    {
        public OrderMaster order { get; set; }
        public List<OrderDetail> orderDetails { get; set; }
    }
}

Step-6: Add a new Controller.

  • Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for show nested data in a webgrid.

Here I have added "List" Action into "Order" Controller. Please write this following code

public ActionResult List()
{
    List<OrderVM> allOrder = new List<OrderVM>();
 
    // here MyDatabaseEntities is our data context
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var o = dc.OrderMasters.OrderByDescending(a => a.OrderID);
        foreach (var i in o)
        {
            var od = dc.OrderDetails.Where(a => a.OrderID.Equals(i.OrderID)).ToList();
            allOrder.Add(new OrderVM { order= i, orderDetails = od });
        }
    }
    return View(allOrder);
}

Step-8: Add view for the Action & design.

  • Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

NOTE " Please Rebuild solution before add view

Html Code
@model IEnumerable<MVCNestedWebgrid.ViewModel.OrderVM>

@{
    ViewBag.Title = "Order List";
    WebGrid grid = new WebGrid(source: Model, canSort: false);
}
<div id="main" style="padding:25px; background-color:white;">
    @grid.GetHtml(
    htmlAttributes: new {id="gridT", width="700px" },
    columns:grid.Columns(
            grid.Column("order.OrderID","Order ID"),
            grid.Column(header:"Order Date",format:(item)=> string.Format("{0:dd-MM-yyyy}",item.order.OrderDate)),
            grid.Column("order.CustomerName","Customer Name"),
            grid.Column("order.CustomerAddress","Address"),
            grid.Column(format:(item)=>{
                WebGrid subGrid = new WebGrid(source: item.orderDetails);
                return subGrid.GetHtml(
                    htmlAttributes: new { id="subT" },
                    columns:subGrid.Columns(
                            subGrid.Column("Product","Product"),
                            subGrid.Column("Quantity", "Quantity"),
                            subGrid.Column("Rate", "Rate"),
                            subGrid.Column("Amount", "Amount")
                        )                   
                    );
            })
        )
    )
</div>
Css Code
<style>
th, td {
        padding:5px;
    }
    th
    {
        background-color:rgb(248, 248, 248);       
    }
    #gridT,  #gridT tr {
        border:1px solid #0D857B;
    }
    #subT,#subT tr {
        border:1px solid #f3f3f3;
    }
    #subT {
        margin:0px 0px 0px 10px;
        padding:5px;
        width:95%;
    }
    #subT th {
        font-size:12px;
    }
    .hoverEff {
        cursor:pointer;
    }
    .hoverEff:hover {
        background-color:rgb(248, 242, 242);
    }
    .expand {
        background-image: url(/Images/pm.png);
        background-position-x: -22px;
        background-repeat:no-repeat;
    }
    .collapse  {
        background-image: url(/Images/pm.png);
        background-position-x: -2px;
        background-repeat:no-repeat;
    }
</style>
Write the following Jquery code for make webgrid collapsible
<script>
    $(document).ready(function () {
        var size = $("#main #gridT > thead > tr >th").size(); // get total column
        $("#main #gridT > thead > tr >th").last().remove(); // remove last column
        $("#main #gridT > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
        $("#main #gridT > tbody > tr").each(function (i, el) {
            $(this).prepend(
                    $("<td></td>")
                    .addClass("expand")
                    .addClass("hoverEff")
                    .attr('title',"click for show/hide")
                );
            //Now get sub table from last column and add this to the next new added row
            var table = $("table", this).parent().html();
            //add new row with this subtable
            $(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
            $("table", this).parent().remove();
            // ADD CLICK EVENT FOR MAKE COLLAPSIBLE
            $(".hoverEff", this).live("click", function () {
                $(this).parent().closest("tr").next().slideToggle(100);
                $(this).toggleClass("expand collapse");
            });
        });
        //by default make all subgrid in collapse mode
        $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
            $(this).toggleClass("expand collapse");
            $(this).parent().closest("tr").next().slideToggle(100);
        });    
    });
</script>

 

Best ASP.NET MVC 6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: ASP.NET MVC vs ASP.NET - Which is better?

clock June 3, 2016 22:54 by author Dan

When developers start to build new web projects they face two options- either using ASP.NET MVC framework or ASP.NET web forms. These days, more and more companies are however choosing the MVC based framework to revise their existing sites significantly or to develop new ones. The framework has a multitude of benefits as well as technical goodies which have made it the darling among the developers.

MVC, short for Model-View-Controller is an architectural pattern that helps in division of an application into three basic components- the controller, the model and the view. This framework is a great alternative to the web forms pattern when creating applications since it is highly testable as well as lightweight presentation framework. It comes integrated with all current .NET features like authentication based on membership as well as master pages. Most developers are quite familiar with the pattern. Here is a low-down on the advantages that the MVC based framework offers over the web forms.

Separating application tasks or concerns- A huge advantage in the framework is that it clearly separates Business Logic, Data, Model, UI, test-driven development and testability. Core contracts of the framework are interface-based for which mock objects may be used for the testing. These mock objects are simulated objects imitating the behaviours of application's actual objects. The application can be unit-tested without making the controllers run, making the testing more flexible as well as fast. Any framework may be used for the testing.

Clientcaching

Silverlight makes this available to us. When we integrate Silverlight full advantage may be taken of the feature. This leads to faster application loading; in fact some part of processing may be done through web browsers, this makes the execution of client site as well as the server side a lot faster. You can even integrate JQuery and MVC so that the code written runs in browser, taking away a huge load away from the server.

HTML size

In ASP.NET there is a huge problem in the HTML size of view state as well as controls. All data rendered is stored by view state with the final result being the final HTML getting too large. For those on slow internet connections, the loading time will be slow as well as delayed. The current framework takes care of that problem since the view state concept is absent here.

Supporting ASP.NET routing

This URL-mapping component is very powerful, letting you build applications with searchable and comprehensible URLs. Through this there is no need for URLs to include extensions of file-names since the design supports patterns of URL naming and these work good enough for SEO or search engine optimization as well as REST or representational state transfer addressing.

Pluggable as well as extensible framework

The design of MVC's components makes them easily customizable or replaceable. Individual view engine, action-method parameter serialization, URL routing policy as well as other components can be plugged in. The use of DI or Dependency Injection and IOC or Inversion of Control container models is also supported. With DI you can inject objects into classes and it does not rely on class for creation of object itself. The testing is made easier by the condition imposed that when an object is required by another object then another object should be sourced from an external source like configuration file.

The biggest advantage of ASP.NET MVC platform is that it contains all the features as well as advantages of .NET since the basis is the same for both. However, some disadvantages are that understanding codes during the process of customization may not be an easy process. Another problem is the cost- the start-up costs are much higher in the MVC platform when compared to the web form based one. But looking at the benefits that are enjoyed by the developers and the end result, this is but a small price to pay for. You can get in touch with a asp.net application development company who can help you develop web apps that are stable, scalable and secure.

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Add the Store Locator in ASP.NET MVC Application

clock April 22, 2016 23:13 by author Dan

Recently, a reader wrote in and asked what steps would be necessary to include a “Directions” link with each marker in the map so that, when clicked, the user would see the driving directions from the address they entered and the store of interest. I decided to update the ASP.NET MVC application to include this new feature request. Now, the results page shows a “Directions” link in both the grid of nearby stores and in the info window that pops up when you click a map marker. Clicking the “Directions” link opens a new browser window and loads Google Maps, showing the directions from the user-entered address to the selected store’s address.

To show the driving directions I send the user to the following URL: http://maps.google.com/maps?f=d&source=s_d&saddr=startingAddress&daddr=destinationAddress.

When the user is sent to the store locator page, the user-entered address (a/k/a, the starting address) is passed through the querystring via a field named Address, so we already know the starting address. But how do we get our hands on the destination address? Recall that view is passed a model that is a collection of NearbyStoreLocation objects; the NearbyStoreLocation class has properties like Address (the street address), City, Region, PostalCode, and so forth. We can build up the address by concatenating these various address parts.

Rather than requiring the view to build up the address, I added a new read-only property to the NearbyStoreLocation class named FormattedAddress, which returns an address Google Maps can parse by piecing together the address-related properties into a string.

public string FormattedAddress
{
get
{
var addrPieces = new List<string>(5);
if (!string.IsNullOrEmpty(this.Address))
addrPieces.Add(this.Address);
if (!string.IsNullOrEmpty(this.City))
addrPieces.Add(this.City);
if (!string.IsNullOrEmpty(this.Region))
addrPieces.Add(this.Region);
if (!string.IsNullOrEmpty(this.CountryCode))
addrPieces.Add(this.CountryCode);
if (!string.IsNullOrEmpty(this.PostalCode))
addrPieces.Add(this.PostalCode);
return string.Join(", ", addrPieces.ToArray());
}
}

In the view, the link to the directions can be build like so:

<a target="_blank" href="http://maps.google.com/maps?f=d&source=s_d&saddr=<%=Server.UrlEncode(Request.QueryString["Address"]) %>&daddr=<%=Server.UrlEncode(store.FormattedAddress) %>">Directions</a>

And that’s it! Adding the Directions link to the info popup window is a tad more involved because the quotation marks must be escaped using \”. Happy Programming!

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET 5 Hosting - ASPHostPortal :: SEO For ASP.NET Web Sites

clock December 16, 2015 00:36 by author Kenny

SEO For ASP.NET Web Sites

One of the main sources of audience for these internet applications are the Search Engines like Google, Bing, Yahoo etc. Hence, the end application should not only handle your business problems efficiently but also follow some simple rules so that it yields good results in internet arena. This article, will list some of the simple guidelines which you need to consider if your Asp.Net application is an internet site.

1.    Add descriptive and unique Page Title for every page

Every page in your website should have a unique and descriptive page title that can describe what the page offers. You can set the Page Title either declaratively or in the code behind file. Refer below,

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" Title="My Home Page"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

In code behind,

Page.Title = "My Home Page";

2.    Links should be hyperlinks, no linkbutton or javascript navigation for crawlable links

Make sure all your links in your page are hyperlinks. Search engines can crawl a page only if it is linked through a hyper link (anchor tag). Javascript navigations are not search engine friendly since search engines will not understand it.

3.    Use javascript navigation for site related pages that have no search values

Page rank is distributed across the links on your page. Some of the internal website pages like About us, disclaimer, Registration, login, contact us, user profile pages can be navigated through javascript so that the page rank are not distributed to them. Doing like this will make rest of the crawlable content links benefited.

4.    Add Meta Keyword and Description tag for every page

Add Meta keyword and Meta description tag with relevant contents. Search engines will use these tags to understand what the page offers. You can dynamically set the meta tags from codebehind file using the below code,

HtmlHead head = (HtmlHead)Page.Header;

 HtmlMeta metasearch1 = new HtmlMeta();

 HtmlMeta metasearch2 = new HtmlMeta();  

 metasearch1.Name = "descriptions";

 metasearch1.Content = "my personal site";

 head.Controls.Add(metasearch1);

 metasearch2.Name = "keywords";

 metasearch2.Content = "ASP.Net,C#,SQL";

 head.Controls.Add(metasearch2);

The above code will add the below Meta tags to output html.

<meta name="descriptions" content="my personal site" />

<meta name="keywords" content="ASP.Net,C#,SQL" />

In ASP.Net 4.0, Microsoft added 2 new properties on the Page directive (Page object) that lets you to define the Meta keywords and Description declaratively and dynamically from codebehind.

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" MetaKeywords="asp.net,C#" MetaDescription="This is an asp.net site that hosts asp.net tutorials" CodeFile="Default.aspx.cs" Inherits="_Default" %>

In codebehind,

protected void Page_Load(object sender, EventArgs e)

    {

        Page.MetaKeywords = "asp.net,C#";

        Page.MetaDescription = "This is an asp.net site that hosts asp.net tutorials.";

    }

The similar can thing can be achieved in previous versions of .Net Framework by using a custom BasePage class.

5.    Make descriptive urls

Make your website URL descriptive. URL’s that has lots of query string values, numeric ids are not descriptive. It will provide enough information what the page offers. For example, http://www.example.com/products.aspx?catid=C91E9918-BEC3-4DAA-A54B-0EC7E874245E is not descriptive as http://www.example.com/Windows-Hosting

Apart from other parameters, search engines will also consider the website url to match your page for a searched keyword.



ASP.NET Hosting - ASPHostPortal.com : How to Migrating From ASP.NET Web API 2 to MVC 6

clock October 13, 2015 08:54 by author Kenny

How to Migrating From ASP.NET Web API 2 to MVC 6

If you create a new MVC 6 project from the default starter template, it will contain the following code in the Startup class, under ConfigureServices method:

 // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
 // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
 // services.AddWebApiConventions();

This pretty much explains it all – the Compatibility Shim is included in an external package, Microsoft.AspNet.Mvc.WebApiCompatShim and by default is switched off for new MVC projects. Once added and enabled, you can also have a look at the UseMvc method, under Configure. This is where central Web API routes can be defined:

      app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" });
            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });

Inheriting from ApiController

Since the base class for Web API controllers was not Controller but ApiController, the shim introduces a type of the same name into MVC 6.

While it is obviously not 100% identical to the ApiController from Web API, it contains the majority of public proeprties and methods that you might have gotten used to – the Request property, the User property or a bunch of IHttpActionResult helpers.

Returning HttpResponseMessage

The shim introduces the ability to work with HttpResponseMessage in MVC 6 projects. How is this achieved? First of all, the Microsoft.AspNet.WebApi.Client package is referenced, and that brings in the familiar types – HttpResponseMessage and HttpRequestMessage.

On top of that, an extra formatter is injected into your application – HttpResponseMessageOutputFormatter. This allows you to return HttpResponseMessage from your actions, just like you were used to doing in Web API projects!

How does it work under the hood? Remember, in Web API, returning an instance of HttpResponseMessage bypassed content negotiation and simply forwarded the instance all the way to the hosting layer, which was responsible to convert it to a response that was relevant for a given host.

In the case of MVC 6, the new formatter will grab your HttpResponseMessage and copy its headers and contents onto the Microsoft.AspNet.Http.HttpResponse which is the new abstraction for HTTP response in ASP.NET 5.

As a result such type of an action as the one shown below, is possible in MVC 6, and as a consequence it should be much simpler to migrate your Web API 2 projects.

public HttpResponseMessage Post()
{
    return new HttpResponseMessage(HttpSattusCode.NoContent);
}

Binding HttpRequestMessage

In Web API it was possible to bind HttpRequestMessage in your actions. For example this was easily doable:

    [Route("test/{id:int}")]
    public string Get(int id, HttpRequestMessage req)
    {
        return id + " " + req.RequestUri;
    }
    [Route("testA")]
    public async Task<TestItem> Post(HttpRequestMessage req)
    {
        return await req.Content.ReadAsAsync<TestItem>();
    }

The shim introduces an HttpRequestMessageModelBinder which allows the same thing to be done under MVC 6. As a result, if you relied on HttpRequestMessage binding in Web API, your code will migrate to MVC 6 fine.

How does it work? The shim will use an intermediary type, HttpRequestMessageFeature, to create an instance of HttpRequestMessage from the ASP.NET 5 HttpContext.

HttpRequestMessage extensions

Since it was very common in the Web API world to use HttpResponseMessage as an action return type, there was a need for a mechanism that allowed easy creation of its instances. This was typically achieved by using the extension methods on the HttpRequestMessage, as they would perform content negotiation for you.

HttpError

If you use/used the CreateErrorResponse method mentioned above, you will end up relying on the HttpError class which is another ghost of the Web API past rejuvenated by the compatibility shim.

HttpError was traditionally used by Web API to serve up error information to the client in a (kind of) standardized way. It contained properties such as ModelState, MessageDetail or StackTrace.

It was used by not just the CreateErrorResponse extension method but also by a bunch of IHttpActionResults – InvalidModelStateResult, ExceptionResult and BadRequestErrorMessageResult. As a result, HttpError is back to facilitate all of these types.

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Check Duplicate User Names In ASP.NET Web Pages Sites

clock October 5, 2015 11:39 by author Kenny

How to Check Duplicate User Names In ASP.NET Web Pages Sites

The Web Pages Starter Site template provides a useful starting point for developing a Razor Web Pages site that includes membership. But it doesn't include any mechanism for preventing duplicate user names. This article offers one solution to the problem that uses jQuery.

If you ask how to prevent duplicate user names in forums, one of the suggestions that is often put forward is to apply a unique constraint in the database column that holds the user name. Any attempt to submit a duplicate value will result in an exception being raised in the relevant database provider. You can catch this exception and show the user an appropriate message. This works but it's a fairly clunky solution. And many people feel that you should not use exceptions as a means to manage your business rules.

The solution featured in this article uses AJAX to query the database and to give the user immediate feedback when they enter their chosen user name. The AJAX call requests a page that exists purely to query the database to see if the selected user name is already in use. The solution also includes a server side chekc to ensure that users who have disabled JavaScript so not slip through the net. The solution requires a couple of amendments to the Register.cshtml file in the Starter Site, and the addition of 3 files. But first, the changes to the Register.cshtml page. The first change is in the inclusion of a JavaScript file called dupecheck.js.

@* Remove this section if you are using bundling *@
@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/dupecheck.js"></script>
}

And the second is the server side check to see if the username is in use:

if(Functions.IsDuplicate(email)){
    ModelState.AddError("email", "User name is already taken");
}

I placed this in the if(IsPost) section just after the initial variables that represent the submitted values (email, password and confirmPassword) are declared. The code calls a function named IsDuplicate. The function is declared in a file called Functions.cshtml which is placed in a folder called App_Code:

@functions {
    public static bool IsDuplicate(string username){
        var db = Database.Open("StarterSite");
        var commandText = @"SELECT COUNT(Email) FROM UserProfile WHERE Email = @0";
        return (int)db.QueryValue(commandText, username) > 0;
    }
}

Note that the name of the folder is important. The function returns a bool. The value of the bool is determined as a result if the SQL query which gets a count of the rows containing the provided user name. By default, the Starter Site uses a column called Email in the UserProfile table for the storage of user names. This function is also called in a separate file named DupeCheck.cshtml. This file is placed in the root of the site:

@{
    Layout = null;
    if(IsAjax){
        var username = Request["username"];
        var result = Functions.IsDuplicate(username);
        Json.Write(new { isDupe = result }, Response.Output);
    }
}

DupeCheck.cshtml is designed to work exclusively with AJAX. The code includes an instruction to nullify any layout pages that might have been set in a _PageStart file, and then it uses the IsAjax property to determine if the page has been requested via an AJAX call. If it has, it uses the IsDuplicate method to check the availability of the posted username and returns the result to the calling code. The result is an anonymous type that has one propery: isDupe, which is a boolean. The anonymous type is serialised to JSON by the Json helper.

The final part of the solution is the dupecheck.js file. This uses jQuery:

$(function () {
    $('#email').change(function () {
        $.post(
            '/DupeCheck',
            { username: $(this).val() },
            function (data) {
                var emailValidation = $('span[data-valmsg-for="email"]');
                if (data.isDupe) {
                    if (emailValidation.hasClass('field-validation-valid')) {
                        emailValidation.removeClass('field-validation-valid');
                        emailValidation.addClass('field-validation-error');
                        emailValidation.text('That name is already taken!');
                    }
                } else {
                    if (emailValidation.hasClass('field-validation-error')) {
                        emailValidation.removeClass('field-validation-error');
                        emailValidation.addClass('field-validation-valid');
                        emailValidation.text('');
                    }
                }
            },'json'
        );
    });
});

An event handler is attached to the change event of the user name input (which has an id if email in the Starter Site). The current value is posted to the DupeCheck.cshtml page via AJAX. The code above checks the response from the server to see if the value is a duplicate, and if it is, an appropriate error message is displayed to the user.

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Easy to Design Pie Chart and Donut Chart in ASP.NET

clock September 28, 2015 12:40 by author Kenny

Easy to Design Pie Chart and Donut Chart in ASP.NET

D3.js stands for Data-Driven Document. It is a JavaScript library using which we can manipulate documents based on data. The data can be fetched using multiple ways like Web Services, WCF Services, REST APIs or the relatively new Microsoft ASP.NET Web API amongst many others. Using D3, you can bind the data to the Document Object Model (DOM) and present that data with rich visualizations. D3 internally makes use of CSS, HTML and SVG capabilities to make your data presentable. It is powerful, fast and supports large datasets and dynamic behaviors for interactions and powerful and smooth animations.

D3.js provides easy and declarative selections of DOM nodes using W3C Selector APIs. D3 Selector APIs provides number of methods to manipulate nodes. For example –

  • Setting attributes and applying rich styles
  • Registering Event Listeners
  • You can add, remove and sort DOM nodes
  • You can change the HTML or the text contents of HTML elements
  • You can also have a direct selection/access to the DOM as each selection is an array of nodes

Likewise, we have various features of D3.js selectors which we can use to present data to our DOM nodes.

A simple selector example is the following:

var bodySelection = d3.select('body').style('background-color', 'blue');

In the above example, we are selecting body and changing its background color to blue. Another example would be as follows:

var divSelection = d3.selectAll('div').style('background-color', 'yellow');

In the above example, we are selecting all divs and changing its background color to yellow. If you are familiar with jQuery, the syntax looks similar to jQuery selectors or HTML5 Selectors.

D3 allows us to bind the data to the DOM elements and their attributes using a Data method which takes an array. For example:

d3.selectAll("div")
  .data([200,300,400,100])
  .style("height", function (data) { return data + "px"; });

In the above example, we are selecting all the div’s on the page and based on the index, the first value of an array will be passed to first div, second value to second div and so on.

In D3, you can also make use of Enter and Exit selector methods to create new nodes for incoming data, and remove outing nodes that are no longer used.

You can also apply transitions to nodes using D3. For example –

var area = d3.select('body')
            .append('svg')
            .attr('width', 500)
            .attr('height', 500);
 
var circle = area.append('rect')
                 .attr('width', 100)
                 .attr('height', 100)
                 .attr('fill', 'red');
 
circle.transition()
      .duration(2000)
      .delay(2000)
      .attr('width', 400)
      .each('start', function () {
            d3.select(this).attr('fill', 'green');})
      .transition()
      .duration(2000)
      .attr('height', 400)
      .transition()
      .duration(2000)
      .attr('width', 50)
      .transition()
      .duration(2000)
      .attr('height', 50)
      .each('end', function () {
            d3.select(this).attr('fill', 'blue'); });

In the above example, we are drawing a Rectangle and applying the transition to the same. Likewise, we can make use of various features of D3.js to present our data using rich visualizations.

A Quick overview of ASP.NET Web API

REST(REpresentational State Transfer) has emerged as the prominent way to create web services. By using REST we can build loose coupled services with data available on the web over HTTP protocol.

ASP.NET Web API is a platform for building RESTful applications. ASP.NET Web API is a framework using which we can build HTTP Services which can be called from a broad range of clients, browsers and mobile devices. ASP.NET Web API is the defacto standard of creating web services and replaces WCF.

When we think about exposing data on the web, we usually talk about four common operations which we use on a daily basis in our apps – CREATE, RETRIVE, UPDATE, DELETE.

We call these operations as CRUD operations. REST provides 4 basic HTTP verbs which we can map to our CRUD operations as described here - POST – CREATE, GET – RETRIVE, PUT – UPDATE, DELETE – DELETE.

By using REST, if you can connect to the web, any application can consume your data. When the data is pulled or pushed by using REST, the data is always serialized into or de-serialized from JSON or XML.

Setting up the application and ASP.NET Web API

To start designing the Pie chart and Donut chart, use the following tools and technologies:

  • Microsoft Visual Studio 2013 (Express or Professional)
  • Microsoft SQL Server 2012 (Express or Developer)
  • jQuery
  • D3.js
  • ASP.NET WEB API

Let’s first design the table where we can add our data. To design the table, open SQL Server Management Studio and write the following script:

CREATE TABLE [dbo].[CityPopulationTable](
    [CityID] [int] IDENTITY PRIMARY KEY,
    [CityName] [nvarchar](30) NULL,
    [Population] [int] NULL
)

Create an ASP.NET Web application by choosing Web Forms template. Then add the Entity Framework, jQuery and D3.js libraries into our web application using NuGet.

Once you add these libraries, right click on the Models folder in our Web application under Solution Explorer, and click on Add New Item. Choose Data  > ADO.NET Entity Data Model.

Using Entity Data Model Wizard, connect to our database and choose CityPopulationTable.

It’s time to implement the ASP.NET Web API into our project. Right click the web application and add a new folder with the name Controllers.

After adding the Web API, open Global.asax file and import two namespaces as shown here:

using System.Web.Http;
using System.Web.Routing;

Also add the following code to the Application_Start method –

GlobalConfiguration.Configure(WebApiConfig.Register);

The above line registers the Web API route in our web application. Now under App_Start folder, you will find WebApiConfig.cs file. Open this file and write the following code:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
 
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.Remove(config.Formatters.XmlFormatter);
}

In the above code, we are configuring Web API to make use of JSON formatter with camel casing, as most of the JavaScript developer will expect JSON output in Camel casing.

Now modify the Get method of our Web API controller as shown here:

public class PieChartController : ApiController
{
    NorthwindEntities dataContext = new NorthwindEntities();
    // GET api/piechart
    public IEnumerable<CityPopulationTable> Get()
    {
        return dataContext.CityPopulationTables.ToList();
    }
}

In the above code, we have created an object of our Entity Data model which will give access to the tables. Then we are returning an IEnumerable of our object CityPopulationTables.

Let us design our Pie chart and Donut chart using the Web API data shown in above:

Creating D3 Charts

Add a HTML page with the name ‘CityPolulationPieChart.html’. Once you add the page, we will reference the jQuery and D3.js file in the page:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Pie Chart Example</title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/d3.js"></script>
</head>

We will make use of jQuery AJAX function to fetch the data from our Web API and display it in a Pie and Donut chart. Let’s add a DOM ready function into our <body> tag. In this function, we will first declare two arrays. First array will hold the data for our chart and the second array will hold the colors which we will use for our chart:

$(function () {
            var chartData = [];
            var colors = [];
});

In the next step, we will fetch the data from our Web API using jQuery $.ajax function. Add this code after our array declaration:

$.ajax({
        type: "GET",
        url: "api/PieChart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            $.each(result, function (i,j) {
                chartData.push(j.population);
                var currentColor = '#' + Math.floor(Math.random() * j.population+5566656).toString(16);
                colors.push(currentColor);
            });
            console.log(chartData);}
        error: function (msg) {
            $("#result").text(msg);
        }
});

Note: Although I have used success and error here for devs using an older version of jQuery, these methods have been deprecated from jQuery 1.8. You should replace them with .done() and fail().

In the above code, we are using a GET request with the Web API URL and the type of data set to JSON. On successful completion of the request, we are running a loop using $.each() which will push the fetched data into our chartData array. We are also generating colors and adding them into our colors array.

Now it’s time to use the D3 selector. We will use D3 selector to select the body and will append the SVG element to the same by setting its height and width. Add this code after console.log function. The code is shown below –

var radius = 300;
var colorScale = d3.scale.ordinal().range(colors);
                    
var area = d3.select('body').append('svg')
             .attr('width', 1500)
             .attr('height', 1500);

Also note that we are using the scale function of D3 which allows us to set the ordinal scale with the range to set the scale’s output range. We have also added a variable called radius which is set to 300.

The next step is to group the elements and draw an arc into our SVG as shown in the following code:

var pieGroup = area.append('g').attr('transform', 'translate(300, 300)');
var arc = d3.svg.arc()
                .innerRadius(0)
                .outerRadius(radius);

In the above code, we are using radius variable as the outer radius and fixing the inner radius to 0. As the next step, use a pie layout available under D3. Then pass the chart data and append it to our group ‘g’. The code is shown below –

var pie = d3.layout.pie()
       .value(function (data) { return data; })
var arcs = pieGroup.selectAll('.arc')
       .data(pie(chartData))
       .enter()
       .append('g')
       .attr('class', 'arc');

Also observe, we are using D3 selector to select arc class added at the end, which will select all the elements which has a class arc. In the last step,  append the path and fill the color from our array. We will also display the population data as text to our pie chart. The code is shown below –

arcs.append('path')
    .attr('d', arc)
    .attr('fill', function (d) { return colorScale(d.data); });
 
arcs.append('text')
    .attr('transform', function (data) { return 'translate(' + arc.centroid(data) + ')'; })
    .attr('text-anchor', 'middle')
    .attr('font-size', '1em')
    .text(function (data) { return data.data; });

Donut Chart

Designing a Donut chart is very simple. Just change the inner radius to something higher than zero. I am making it 200. The code is as shown here:

var arc = d3.svg.arc()
        .innerRadius(200)
        .outerRadius(radius);

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC 6 Hosting - ASPHostPortal :: Remote Validation in ASP.NET MVC

clock August 24, 2015 08:07 by author Kenny

Remote Validation in ASP.NET MVC

ASP.NET is an open-source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side.  It's all done set up model and controller which is pretty neat. 

Using the Code

To implement remote validation in an application we have two scenarios, one is without an additional parameter and the other is with an additional parameter. First we create an example without an additional parameter. In this example we check whether a username exists or not. If the username exists then that means the input user name is not valid. We create a view model class "UserViewModel" under the Models folder and that code is:

using System.Web.Mvc;  
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

 

Now we create a static data source, in other words we create a static list of UserViewModel in which we could check whether a username exists or not. You can also use the database rather than a static list. The following code snippet is for StaticData.

using RemoteValidation.Models;  
using System.Collections.Generic;  
 
namespace RemoteValidation.Code   
{  
    public static class StaticData   
    {  
        public static List < UserViewModel > UserList   
        {  
            get {  
                return new List < UserViewModel >   
                {  
                    new UserViewModel   
                    {  
                        UserName = "User1", Email = "user1@web.com"  
                    },  
                    new UserViewModel   
                    {  
                        UserName = "User2", Email = "user2@web.com"  
                    }  
                }  
            }  
        }  
    }  

 

Now we create a controller "ValidationController" in which we create an action method to check whether a user name exists or not and return a result as a JSON format. If the username exists then it returns false so that the validation is implemented on the input field. The following code snippet shows ValidationController under the Controllers folder.

using RemoteValidation.Code;  
using System.Linq;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class ValidationController: Controller   
    {  
        [HttpGet]  
        public JsonResult IsUserNameExist(string userName)   
        {  
            bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower())).FirstOrDefault() != null;  
            return Json(!isExist, JsonRequestBehavior.AllowGet);  
        }  
    }  
}

 

Now we add remote validation on the UserName of the UserViewModel property as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  

 

As in the preceding code snippet, the IsUserNameExist is a method of ValidationController that is called on the blur of an input field using a GET request. Now we create UserController under the Controllers folder to render a view on the UI.

using RemoteValidation.Models;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class UserController: Controller   
    {  
        [HttpGet]  
        public ActionResult AddUser()   
        {  
            UserViewModel model = new UserViewModel();  
            return View(model);  
        }  
    }  

Now we add jquery.validate.js and jquery.validate.unobtrusive.js to the project and create a bundle as in the following code snippet.

using System.Web.Optimization;  
 
namespace RemoteValidation.App_Start   
{  
    public class BundleConfig   
    {  
        public static void RegisterBundles(BundleCollection bundles)   
        {  
            bundles.Add(new StyleBundle("~/Content/css").Include(  
                "~/Content/css/bootstrap.css",  
                "~/Content/css/font-awesome.css",  
                "~/Content/css/site.css"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
                "~/Scripts/jquery-{version}.js"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
                "~/Scripts/jquery.validate*"));  
        }  
    }  

Thereafter we add the following keys in the web.config file.

<add key="ClientValidationEnabled" value="true" />   
<add key="UnobtrusiveJavaScriptEnabled" value="true" />  
 
 

Thereafter we create a view for the AddUser action method. The following code snippet is for the AddUser view.

@model RemoteValidation.Models.UserViewModel  
 
< div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Add User < /div>    
    <div class="panel-body">    
        @using (Html.BeginForm())    
        {    
            <div class="form-horizontal">    
                <div class="form-group">    
                    @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.UserName)    
                    </div > < /div>    
                <div class="form-group">    
                    @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.Email)    
                    </div > < /div>                    
                <div class="form-group">    
                    <div class="col-lg-9"></div > < div class = "col-lg-3" > < button class = "btn btn-success"  
                     id = "btnSubmit"  
                     type = "submit" > Submit < /button>    
                    </div >
               < /div>    
            </div >  
} < /div>    
</div >   
@section scripts   
{  
    @Scripts.Render("~/bundles/jqueryval")  

Let's run the application and put values into the user name field to execute the remote validation as in the following image.

Figure 1: Remote validation on user name


Now we move to another option, we pass an additional parameter in the remote validation. We pass both the user name and email as a parameter and check whether the username and email combination exist or not on the email input. That's why we add one more method in ValidationController as in the following code snippet for it.

[HttpGet]  
public JsonResult IsUserExist(string email, string userName)   
{  
    bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower()) && u.Email.ToLowerInvariant().Equals(email.ToLower())).FirstOrDefault() != null;  
    return Json(!isExist, JsonRequestBehavior.AllowGet);  

Now we call this method on the Email property of UserViewModel as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        [Remote("IsUserExist", "Validation", ErrorMessage = "User already exist", AdditionalFields = "UserName")]  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

As in the preceding code snippet, we are passing an additional field using AdditionalFields in Remote. If we must pass more than one parameter then these will be comma-separated. Now run the application and the result will be as shown in the following image.  



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in