Videos | Podcasts

Performing Validation in an ASP.NET MVC Application
AzamSharp
Published Date: 11/29/2009 10:39:24 AM
Views: 4930

Abstract:
Validation is one of the most important aspects of an application. ASP.NET MVC framework provides multiple ways to validate the user input. In this article we are going to demonstrate how to perform validation in an ASP.NET application using Controller action, IDataErrorInfo and DataAnnotations methods.

Simple Validation:

The most simple way to perform validation is to perform it inside the Controller. The controller will be responsible for checking for the validity of the data. Let's check out the code for the view.


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Simple Validation</h2>
        
   <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   
   LastName: <%= Html.TextBox("LastName")%>
    
    <input type="submit" value="Save" />
    
    <% } %>

</asp:Content>


As, you can see the view is very simple and consists of FirstName and LastName TextBoxes. The submit button will submit the form and invoke the "SimpleValidation" action of the controller.

The controller used in this case is the HomeController. The SimpleValidation action is responsible for performing the validation on the data. The implementation of the SimpleValidation action is shown below:


 public ActionResult SimpleValidation(Customer customer)
        {
            if(String.IsNullOrEmpty(customer.FirstName))
                ModelState.AddModelError("FirstName","FirstName cannot be blank!");

            if(String.IsNullOrEmpty(customer.LastName))
                ModelState.AddModelError("LastName","LastName cannot be blank!");

            if (!ModelState.IsValid)
                return View("SimpleValidation");

            return View("Confirmation");
        }



The SimpleValidation action accepts the Customer object as an input parameter. This is performed by Model Binders feature in ASP.NET MVC framework. You can check out the article on Model Binders here.

Inside the SimpleValidation action the ModelState.AddModelError method is used to populate the error collection of the model. The ModelState.IsValid property represents if there are any errors in the model. If the model is invalid then we simply return the current view which in this case is "SimpleValidation". If the model is valid then we return the "Confirmation" view.

Finally, make the adjustments in the view to display the errors. This is performed by the HTML helpers ValidationMessage as shown below:


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Simple Validation</h2>
        
   <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
        
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   <%= Html.ValidationMessage("FirstName","*") %>
   
   LastName: <%= Html.TextBox("LastName")%>
    <%= Html.ValidationMessage("LastName","*") %>
    
    <input type="submit" value="Save" />
    
    <% } %>

</asp:Content>


Now, run the above page and click on the "submit" page without inputting the values for the FirstName and LastName. You will realize that the page was not submitted successfully since it was invalid. You can even make the errors more visible by using the ValidationSummary HTML helper as shown below:


 <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
        
    <%= Html.ValidationSummary("Errors") %>     
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   <%= Html.ValidationMessage("FirstName","*") %>
   
   LastName: <%= Html.TextBox("LastName")%>
    <%= Html.ValidationMessage("LastName","*") %>
    
    <input type="submit" value="Save" />
    
    <% } %>
    

Validation Using IDataErrorInfo:

The second method of performing validation in an ASP.NET MVC application is by using the IDataErrorInfo class. This method involves the model class to inherit from the IDataErrorInfo interface. The implementation is shown below:


 public class Customer  : IDataErrorInfo
    {
        private string _firstName;
        private string _lastName;
        private Dictionary<String,String> _errors = new Dictionary<string, string>();

        
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if(String.IsNullOrEmpty(value))
                    _errors.Add("FirstName","FirstName cannot be blank!");

                _firstName = value;
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                if(String.IsNullOrEmpty(value))        
                    _errors.Add("LastName","LastName cannot be blank!");

                _lastName = value;
            }
        }
        
        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                    return _errors[columnName];

                return String.Empty;
            }
        }

        public string Error
        {
            get { return String.Empty;  }
        }
    }
      

Using this method the controller action is simplified as the validation is now moved into the model itself. The implementation is shown below:


 public ActionResult ValidationUsingIDataErrorInfo(Customer customer)
        {
            if (!ModelState.IsValid)
                return View("ValidationUsingIDataErrorInfo");

            return View("Confirmation");
        }


Using DataAnnotations:

The DataAnnotations provides the most easiest way to perform validation in an ASP.NET MVC application. It uses attributes to perform validation. The first thing you need to do is to download the DataAnnotations library. You can download it from here. 

http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471

You need to download "Data Annotations Model Binder Sample". Once, it is downloaded you need to build the solution in Visual Studio which will create the "Microsoft.Web.Mvc.DataAnnotations" and System.ComponentModel.DataAnnotations" assemblies. The final step is to set the DataAnnotations default binder to the Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();  in the Global.asax file as shown below:


  protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();

        }

 
Now, in order to use the validation you will simply use the attributes on the model properties as shown below:


 public class Customer
    {
        [Required(ErrorMessage = "FirstName cannot be blank")]
        public string FirstName { get; set; }

        [Required(ErrorMessage ="LastName cannot be blank!")]  
        public string LastName { get; set; }
    }


Conclusion:

In this article we discussed several different ways to perform validation in an ASP.NET MVC application. Depending on the scenario you can choose the technique that fulfill your needs. In the next article we will discuss in detail how to create custom DataAnnotations.

[Download Sample]



Did you like this article?
kick it on DotNetKicks.com Submit
Similar Articles

Implementing Blog Using ASP.NET MVC and MongoDb

Ajaxify your ASP.NET MVC Application

Implementing ViewModel in ASP.NET MVC Application

Using T4 Templates to Create Strongly Typed View Names

Creating Wizard in ASP.NET MVC Part 2

Enter Comment/Feedback

 
 
 
 
 

Comments/Feedbacks