ASP.NET MVC 3 - Performing Model Validation Explicitly




In an MVC application, a View does not have code-behind by default, so performing validation becomes very important. In MVC, model validation can be performed using the following techniques:
  • Using Data Annotations
  • Using Custom Data Annotations
  • Using Asynchronous validations using Remote
  • Using client-side validations using jQuery
In this small article, I have explained the technique of performing validations using ModelState object. This object gets the state of the dictionary object that contains the state of the model and of the model binding validation. The explicit validation mechanism is used when you do not have access to model layer for applying Data-Annotations using partial class and MetedataType which we generally use for ADO.NET EF entities.


For this article, I am using ADO.NET EF with the below table:
image


Step 1: Open Visual Studio and create a new MVC application, name it as ‘MVC3_Validations’. In this project, add a new Model using ADO.NET EF for the above table.

Step 2: To this project, add a new controller of name ‘TestMasterController.cs’ and use the  the following Create methods:

public ActionResult Create()
{
    var Test = new TestMaster();
    return View(Test);
}

//
// POST: /TestMaster/Create

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        TestMaster test = new TestMaster();
        test.TestName = Convert.ToString(collection[0]);
        test.Subject = Convert.ToString(collection[1]);
        test.TestDate = Convert.ToDateTime(collection[2]);
        test.IsApproved = Convert.ToBoolean(collection[3]);

        if (string.IsNullOrEmpty(test.TestName))
        {
            ModelState.AddModelError("TestName",
                "Please Enter the Test Name");
        }

        if (ModelState.IsValidField("TestDate")
            && DateTime.Now > test.TestDate)
        {
            ModelState.AddModelError("TestDate", 
            "Date Must be Greater than current Date");
        }

        if (ModelState.IsValid)
        {
            objContext.AddToTestMasters(test);
            objContext.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }

       
    }
    catch
    {
        return View();
    }
}


The above code uses the if statements to check values entered in the view by the end-user. The errors are registered using ModelState object. Also the IsValidField method of the code verifies whether the model binder was able to assign a value property. This method in the above code is used to check whether the ‘Date’ value entered is parsed or not.

Step 3: Generate Create View from the create method. Set the ValidationSummary method parameter from True to False to view all errors at model level.

Step 4: Run the application, and navigate to the following URL:

hxxp://localhost:1052/TestMaster/Create

Click on the “Create” button and the result will be as shown below:

clip_image002

The above UI shows the Validation errors.

Conclusion: Explicit validations are used for implementing more domain specific validation in ASP.NET MVC using controller class.

Download the entire source code

Will you give this article a +1 ? Thanks in advance




About The Author

Mahesh is having 10 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

comments

1 Response to "ASP.NET MVC 3 - Performing Model Validation Explicitly"
  1. Tatevel Asquez said...
    October 10, 2012 at 5:58 AM

    This is quite informative, as being a beginner to ASP.NET. I have just cleared up my basics and now looking for such great tutorials which are easy to follow and to gain something fruitful from it.

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions