5 min read


ASP.NET MVC 2 Cookbook

ASP.NET MVC 2 Cookbook

A fast-paced cookbook with recipes covering all that you wanted to know about developing with ASP.NET MVC

  • Solutions to the most common problems encountered with ASP.NET MVC development
  • Build and maintain large applications with ease using ASP.NET MVC
  • Recipes to enhance the look, feel, and user experience of your web applications
  • Expand your MVC toolbox with an introduction to lots of open source tools
  • Part of Packt’s Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible



ASP.NET MVC provides a simple, but powerful, framework for validating forms. In this article, we’ll start by creating a simple form, and then incrementally extend the functionality of our project to include client-side validation, custom validators, and remote validation.

Basic input validation

The moment you create an action to consume a form post, you’re validating. Or at least the framework is. Whether it is a textbox validating to a DateTime, or checkbox to a Boolean, we can start making assumptions on what should be received and making provisions for what shouldn’t. Let’s create a form.

How to do it…

  1. Create an empty ASP.NET MVC 2 project and add a master page called Site.Master to Views/Shared.
  2. In the models folder, create a new model called Person. This model is just an extended version of the Person class.Models/Person.cs:

    public class Person {
    [DisplayName(“First Name”)] public string FirstName { get; set; }
    [DisplayName(“Middle Name”)] public string MiddleName { get; set; }
    [DisplayName(“Last Name”)] public string LastName { get; set; }
    [DisplayName(“Birth Date”)] public DateTime BirthDate { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Postcode { get; set; }
    public string Notes { get; set; }

  3. Create a controller called HomeController and amend the Index action to return a new instance of Person as the view model.Controllers/HomeController.cs:

    public ActionResult Index() {
    return View(new Person());

  4. Build and then right-click on the action to create an Index view. Make it an empty view that strongly types to our Person class.
  5. Create a basic form in the Index view.Views/Home/Index.aspx:

  6. We’ll go back to the home controller now to capture the form submission. Create a second action called Index, which accepts only POSTs.Controllers/HomeController.cs:

    [HttpPost] public ActionResult Index(…

  7. At this point, we have options. We can consume our form in a few different ways, let’s have a look at a couple of them now:Controllers/HomeController.cs (Example):

    // Individual Parameters
    public ActionResult Index(string firstName, DateTime birthdate…

    // Model
    Public ActionResult Index(Person person) {

  8. Whatever technique you choose, the resolution of the parameters is roughly the same. The technique that I’m going to demonstrate relies on a method called UpdateModel. But first we need to differentiate our POST action from our first catch-all action. Remember, actions are just methods, and overrides need to take sufficiently different parameters to prevent ambiguity. We will do this by taking a single parameter of type FormCollection, though we won’t necessarily make use of it.Controllers/HomeController.cs:

    [HttpPost] public ActionResult Index(FormCollection form) {
    var person = new Person();


    return View(person);


    The UpdateModel technique is a touch more long-winded, but comes with advantages. The first is that if you add a breakpoint on the UpdateModel line, you can see the exact point when an empty model becomes populated with the form collection, which is great for demonstration purposes.
    The main reason I go back to UpdateModel time and time again, is the optional second parameter, includeProperties. This parameter allows you to selectively update the model, thereby bypassing validation on certain properties that you might want to handle independently.

  9. Build, run, and submit your form. If your page validates, your info should be returned back to you. However, add your birth date in an unrecognized format and watch it bomb. UpdateModel is a temperamental beast.

    ASP.NET MVC 2: Validating MVC

  10. Switch your UpdateModel for TryUpdateModel and see what happens. TryUpdateModel will return a Boolean indicating the success or failure of the submission. However, the most interesting thing is happening in the browser.

    ASP.NET MVC 2: Validating MVC

How it works…

With ASP.NET MVC, it sometimes feels like you’re stripping the development process back to basics. I think this is a good thing; more control to render the page you want is good. But there is a lot of clever stuff going on in the background, starting off with Model Binders.

When you send a request (GET, POST, and so on) to an ASP.NET MVC application, the query string, route values and the form collection are passed through model binding classes, which result in usable structures (for example, your action’s input parameters). These model binders can be overridden and extended to deal with more complex scenarios, but since ASP.NET MVC2, I’ve rarely made use of this. A good starting point for further investigation would be with DefaultModelBinder and IModelBinder.

What about that validation message in the last screenshot, where did it come from? Apart from LableFor and EditorFor, but we also have ValidationMessageFor. If the model binders fail at any point to build our input parameters, the model binder will add an error message to the model state. The model state is picked up and displayed by the ValidationMessageFor method, but more on that later.

Subscribe to the weekly Packt Hub newsletter

* indicates required


Please enter your comment!
Please enter your name here