Data Entry and Validation in ASP.NET MVC Framework Applications

Introduction

The ASP.NET MVC Framework (based on the Model View Controller Design Pattern) is a platform for designing and developing web applications on top of the managed ASP.NET runtime. Since ASP.NET MVC applications doesn't rely on the traditional ASP.NET model, validating user input is a bit tricky. Scott Guthrie states in his blog: "Validating user-input and enforcing business rules/logic is a core requirement of most web applications. ASP.NET MVC 2 includes a bunch of new features that make validating user input and enforcing validation logic on models/viewmodels significantly easier. These features are designed so that the validation logic is always enforced on the server, and can optionally also be enforced on the client via JavaScript."
Reference: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

This article discusses the basics of ASP.NET MVC Framework and how it can be used to perform CRUD operations and implement validation logic in the presentation layer.

Pre-requisites

To execute the code examples illustrated in this article, you should have the following installed in your system:

  • ASP.NET MVC 2.0
  • Microsoft Visual Studio 2008

Alternatively, you can have Microsoft Visual Studio 2010 installed in your system - you'll get the ASP.NET MVC Framework and the necessary templates you need to work embedded there.

The Model View Controller Design Pattern - Why do you need it?

Application that have a mix of data access, business logic and presentation layer code are difficult to test and maintain because of the interdependencies amongst the components. A change in any of such components would incur a change in the components that depend on the component that has changed. The MVC Design Pattern solves these problems by reducing the cohesion amongst the components in an application. It does this by decoupling the data access, business logic, and data presentation and user interaction components resulting in loosely coupled and easily testable components.

The Model View Controller is one of the most popular and widely used of all design patterns. It is used to facilitate testability, promote a cleaner separation of concerns and also for easier maintenance of the application's code. It should be noted that an application's concern can be of two types--the core concerns (these include the application's business logic and data access logic, etc) and cross cutting concerns (these include logging, exception handling, messaging, etc).

The Model View Controller Design Pattern is comprised of the following three core components:

  • Model - it is the component that is responsible for handling the application's business logic and data access components.
  • The View - it is the component that is responsible for presenting the model's data in the user interface.
  • The Controller - it is the component that manages the interaction amongst the other components and invalidates the View based on the Model's state.

What is the ASP.NET MVC Framework?

The ASP.NET MVC Framework is based on the proven time tested MVC Design Pattern and provides you a platform for designing and implementing web applications where you can have a cleaner separation of concerns, better code organization, seamless extensibility, scalability and code reuse. Applications designed using the ASP.NET MVC Framework is easier to test and maintain. Scott Guthrie states in his blog: "One of the benefits of using an MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated."
Reference: http://weblogs.asp.net/scottgu/archive/2007/10/14/aspnet-mvc-framework.aspx

The ASP.NET MVC Framework provides support for the following features:

  • Support for a Test Driven Design model
  • Support for Dependency Injection and IOC containers
  • Support for clean URLs and navigation support
  • Support for REST-based design
  • Pluggable, extensible, and maintainable
  • Support for all existing ASP.NET features that includes, authentication, authorization, membership and role management, state management, etc.

Implementing Validation Logic in ASP.NET MVC Applications

Validating user input in ASP.NET web forms is easy--you have so many controls that help you get the job done. Also, retrieving the data posted from a web form is simple. In ASP.NET MVC applications, you can validate user input using built-in HMTL helper functions and ModelState class.

Model Binding is a powerful feature in ASP.NET MVC Framework. It validates the posted data against the validation rules that have been specified on the model class. If the data being posted doesn't conform to the validation rules, the Model Binding framework appends the errors to the ModelState object. Incidentally, the ModelState object is an instance (it's a Dictionary to be precise) that contains all the errors that have occured due to violation of the validation rules while the data was posted by the web form. You can use the IsValid property of the ModelState class to determine what to do if a validation failure has occured. Here's a code snippet that illustrates this concept:

  [HttpPost]
  public ActionResult Create(FormCollection collection)
  {
  	if (!ModelState.IsValid)
  		return View();
  	else
  		return RedirectToAction("Index", "Home");
  }

Basically, there are two ways in which you can implement validation logic in your ASP.NET MVC application:

  • Using the DataAnnotation validation support to declaratively add validation rules to the business objects in your application
  • Using other validation engine or existing validation frameworks like Castle Validator or the Enterprise Validation Library from Microsoft.



Data Entry and Validation in ASP.NET MVC Framework Applications

Implementing Input Validation Support for ASP.NET MVC Applications

In this section we'll discuss how we can implement input validation logic in our ASP.NET MVC applications. Here's what you need to do:

  1. Open the Microsoft Visual Studio 2010 IDE
  2. Create a new ASP.NET MVC application
  3. Now, create a simple model class similar to what is shown below:

           public class Employee
           {
               public int EmployeeID { get; set; }
               public string FirstName { get; set; }
               public string LastName { get; set; }
           }
     

    As you can see, the Employee class contains three properties implemented using the automated property support in C#.

    The next step is to add a controller for this model class. We'll name it EmployeeController.

  4. Select the "Controllers" folder in the SoultionExplorer window and click on Add->New Controller

    Here's how the EmployeeController class will look:

      using System.Web.Mvc;
      
      namespace CodeGuru.Controllers
      {
          public class EmployeeController : Controller
          {
      
              public ActionResult Index()
              {
                  return View();
              }
      
              public ActionResult Details(int id)
              {
                  return View();
              }
      
              public ActionResult Create()
              {
                  return View();
              } 
      
              [HttpPost]
              public ActionResult Create(FormCollection collection)
              {
                  try
                  {
                      return RedirectToAction("Index");
                  }
                  catch
                  {
                      return View();
                  }
              }        
      
              public ActionResult Edit(int id)
              {
                  return View();
              }
      
              [HttpPost]
              public ActionResult Edit(int id, FormCollection collection)
              {
                  try
                  {
                      return RedirectToAction("Index");
                  }
                  catch
                  {
                      return View();
                  }
              }
      
              public ActionResult Delete(int id)
              {
                  return View();
              }
      
              [HttpPost]
              public ActionResult Delete(int id, FormCollection collection)
              {
                  try
                  {
                      return RedirectToAction("Index");
                  }
                  catch
                  {
                      return View();
                  }
              }
          }
      }
    

    Now, we'll create a strongly typed view for the Employee model created earlier. This would be used to display Employee data to the end user.

  5. Select the Create action method in the Employee controller we created earlier and then right-click and select "Add View" to generate a view for the Employee model.
  6. Select the "Create a Strongly Typed View" checkbox to create a strongly typed view and select CodeGuru.Models.Employee as the model class for this view.

    Once you do this, a strongly typed view would be generated and the mark-up code would look similar to what is shown below:

        <% using (Html.BeginForm()) {%>
               <%: Html.ValidationSummary(true) %>
       
               <fieldset>
                   <legend>Fields</legend>
                   
                   <div class="editor-label">
                       <%: Html.LabelFor(model => model.EmployeeID) %>
                   </div>
                   <div class="editor-field">
                       <%: Html.TextBoxFor(model => model.EmployeeID) %>
                       <%: Html.ValidationMessageFor(model => model.EmployeeID) %>
                   </div>
                   
                   <div class="editor-label">
                       <%: Html.LabelFor(model => model.FirstName) %>
                   </div>
                   <div class="editor-field">
                       <%: Html.TextBoxFor(model => model.FirstName) %>
                       <%: Html.ValidationMessageFor(model => model.FirstName) %>
                   </div>
                   
                   <div class="editor-label">
                       <%: Html.LabelFor(model => model.LastName) %>
                   </div>
                   <div class="editor-field">
                       <%: Html.TextBoxFor(model => model.LastName) %>
                       <%: Html.ValidationMessageFor(model => model.LastName) %>
                   </div>
                   
                   <p>
                       <input type="submit" value="Create" />
                   </p>
               </fieldset>
       
           <% } %>
     

    Now, let's update the model with validation tags and error messages to enforce validation rules. To do this you should add the System.ComponentModel.DataAnnotations namespace to your model class and then decorate its properties using the [Required], [StringLength], [Range], and [RegularExpression] validation attributes provided by this namespace we just added.

  7. Here's how the updated model class would look like:

    using System.ComponentModel.DataAnnotations;
    
      namespace CodeGuru.Models
      {
          public class Employee
          {
              public int EmployeeID { get; set; }
      
              [Required (ErrorMessage="First Name cannot be blank and should be within 25 characters")]
              [StringLength(25)]
              public string FirstName { get; set; }
      
              [Required (ErrorMessage="Last Name cannot be blank and should be within 25 characters")]
              [StringLength(25)]
              public string LastName { get; set; }
          }
      }
    

    One of the amazing things in the validation framework in ASP.NET MVC 2.0 is in its seamless support for both server-side and client-side validation. To enable client-side validation in your ASP.NET MVC application, all you have to do is add the MicrosoftAjax.js and MicrosoftMvcValidation script files as JavaScript references and then make a call to Html.EnableClientValidation() in your code. Refer to the code snippet below:

      <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
      <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
    
    <h2>Create</h2>
    <% Html.EnableClientValidation(); %>

Summary

The ASP.NET MVC Framework provides .NET developers a platform to design and implement web applications in a more structured way, make them testable, maintainable and extendable and, with less code. While designing web applications, you would often need to validate user input and then enforce business rules/logic based on the outcome. The new versions of ASP.NET MVC (version 2.0 and later) comes in with enhanced support for implementing validation logic on your model classes easily .In this article we have had a look at how the Model Binding framework in ASP.NET MVC can be used to implement validation logic.

Suggested Readings

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
http://www.devproconnections.com/article/aspnetmvc/Create-Custom-Validation-Components-in-ASP-NET-MVC-2.aspx

Related Articles





About the Author

Joydip Kanjilal

Microsoft Most Valuable Professional, Author and Speaker. Featured in "MSDN Featured Developer of the Fortnight (India)" a number of times. Winner of Community Credit Awards at www.community-credit.com several times. Authored numerous books and articles in Microsoft .NET and its related technologies. Authored the following books:-- ASP.NET 4.0 Programming (Mc-Graw Hill Publishing) Entity Framework Tutorial (Packt Publishing) Pro Sync Framework (APRESS) Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing) ASP.NET Data Presentation Controls Essentials (Packt Publishing)

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Stories about devastating cyberattacks are plaguing the news. Why? The DNS protocol is easy to exploit. See your network the way hackers do—as an easy target. Learn how you can effectively secure your DNS infrastructure today.

  • You may already know about some of the benefits of Bluemix, IBM's open platform for developing and deploying mobile and web applications. Check out this webcast that focuses on building an Android application using the MobileData service, with a walk-through of the real process and workflow used to build and link the MobileData service within your application. Join IBM's subject matter experts as they show you the way to build a base application that will jumpstart you into building your own more complex app …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds