Page 1 of 1

[ASP.Net MVC2] How to use basic model validation.

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 08 August 2010 - 03:51 PM

In this tutorial I will teach you how to use basic built in MVC2 model validation to protect your application from incorrect user input.

Let's start by describing some context. I have a table in my database called 'Area'.

Posted Image

It has the following fields (id, id of the chief of that area and the name of the area):
  • ID
  • IDJefe
  • Nombre


I also have an Entity Framework .edmx file for my database which creates strongly-typed classes to represent the 'Area'. In my application each, Area object will be a row from the Area table.

I want you to create a new C# class called Area (the same name as the table) and make it a partial. This is so the generated Area class combines with our own custom Area class.

Remember to create the partial class in the same namespace as the .edmx file, that way they can combine!

Posted Image

Now inside of partial class write this in:

namespace <YourNamespaceGoesHere>
{
    [Bind(Include = "IDJefe, Nombre")]
    [MetadataType(typeof(Area_Validation))]
    public partial class Area
    {
        
    }

    public class Area_Validation
    {
        [Required(ErrorMessage = "Jefe is required.")]        
        public int IDJefe { get; set; }

        [Required(ErrorMessage = "Nombre del area is required.")]
        public string Nombre { get; set; }
    }
}


Let's breakdown wants going on.

First, I bind certain fields so they are included in the validation, meaning that can be modified. Everything that is not on the include fields cannot be modified.

Next I tell it to validate using my custom validation class called Area_Validation.

Inside the Area_Validation class we must manually create the fields, and type in the datatype. Unfortunately this method doesn't allow us to have a strongly typed class. No intellisense help. :)

With the ErrorMessage we can type in what error we want to display when the field doesn't pass validation.

Now let's see the process for the Action called Create:

[HttpPost]
public ActionResult Create(Area area, FormCollection values)
{
    if (ModelState.IsValid)
    {
        repo.Add(area);
        repo.Save();
        return RedirectToAction("Details", new { id = area.ID });
    }
    return View(area);
}



When a user tries to save this 'area' object, the ModelState will now verify using our own custom created validation and if failed will pass the invalid fields to the View.

Now let's see the Edit Action:

[HttpPost]
public ActionResult Edit(int id, FormCollection values)
{
    var area = repo.GetArea(id);
    if (TryUpdateModel(area))
    {
        repo.Save();
        return RedirectToAction("Details", new { id = area.ID });
    }
    return View(area);            
}



Same deal, the TryUpdateModel is a built in helper method that tries to update the area and if failed will populate the model with information of invalid fields.

I hope you enjoyed this tutorial!

Is This A Good Question/Topic? 0
  • +

Page 1 of 1