Home > ASP.NET MVC > ASP.NET # MVC # 10– Client Side and Server Side validation for a Strongly typed view using Data Annotation (Model Validation)

ASP.NET # MVC # 10– Client Side and Server Side validation for a Strongly typed view using Data Annotation (Model Validation)

Hi Geeks,

As we know Validations are the most important part of any Web application because only correct data should be entered in to the database.

ASP.NET mvc makes it very easy for the developers to do the client and server side validation for a particular view which is typed with particular model.

Model Validation takes advantage of DataAnnotations, from the System.ComponentModel
namespace

Model Validation is one of the biggest productivity boosters in ASP.NET MVC 2. It replaces tons of hand-written, imperative validation logic with simple, declarative attributes.

Following are the attributes provided by the DataAnnotations  to do the validations.

image

 

STEP I –

suppose we have a model (from which we are going to create a strongly typed view) as follow

public class EmployeeModel
   {
      [Required(ErrorMessage = "Please provide EmpName.")]
      [RegularExpression(pattern:@"^[a-zA-Z \\s]{0,60}$")]
      public string EmpName { get; set; }
      
      [Range(22, 59)]
      public int age { get; set; }
      
      [StringLength(250)]
      public string address { get; set; }

   }

In above model i have covered up three types of Attribute

1)Required – means EmpName is mandatory.

2)RegularExpressionAttribute – which is saying name should be alphabetical with space

2)Range – means age must be in between 22 and 59

3)StringLength – means length of the string limits to 250

STEP II –

We will take a view which as “Index” is strongly typed with above model.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ModelValidation.Models.EmployeeModel>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

   
Home Page

</asp:Content>

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

    <%using (Html.BeginForm("SaveData", "Home"))

      { %>

    <div class="Width100">

        <
div class="Width30">

           
Employee Name

        </div>

        <
div class="Width60">

           
<%:Html.TextBoxFor(c=>c.EmpName) %>

        </div>

       
<%:Html.ValidationMessageFor(c => c.EmpName)%>

    </div>

    <
br />

    <
div class="Width100">

        <
div class="Width30">

           
Age

        </div>

        <
div class="Width60">

           
<%:Html.TextBoxFor(c=>c.age) %>

        </div>

       
<%:Html.ValidationMessageFor(c=>c.age) %>

    </div>

    <
br />

    <
div class="Width100">

        <
div class="Width30">

           
Address

        </div>

        <
div class="Width60">

           
<%:Html.TextBoxFor(c=>c.address) %>

        </div>

    </
div>

    <
input type="submit" id="btnSave" />

   
<%} %>

</asp:Content>

 

In above view we have used Html helper class Html.ValidationMessageFor,which will display the error message for the particular filed passed as a parameter.

We have a Html form whose post method is SaveData so when we click on the btnSave button it will give call to the SaveMethod in the Home controller.

The code at the controller is as follows

       [HttpPost]
       public ActionResult SaveData(EmployeeModel emp)
       {
           if (TryValidateModel(emp))
           { 
           //Put your save logic here
           }
           return View("Index",emp);
       }

TryUpdateModel is all responsible for the validation of the model.

How TryUpdateModel method works???

The TryUpdateModel helper method automatically populates the ModelState collection when it encounters errors while trying to assign form values to properties on the Model object.For example as our  employee model raised an error if you don’t pass name to it as it is required.

You will see the window as follow once you run the page and when click on the save button of it as we haven’t supplied name and age is not between 20 and 60.

image

 

Note:- For client side validation you just have to add the line

<%Html.EnableClientValidation(); %>  at above the html BeginForm tag

and give the reference of the three JavaScript files  as shown below –

  <%Html.EnableClientValidation(); %>

 <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>

  <
script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>

  <
script src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>" type="text/javascript"></script>

    <%using (Html.BeginForm("SaveData", "Home")){ %>

 

 

Thanks,

Advertisements
Categories: ASP.NET MVC
  1. September 9, 2011 at 9:11 am

    nice one and very understandable

  2. April 23, 2013 at 3:34 pm

    Hey there! I just wish to give you a big thumbs up for your excellent info you
    have here on this post. I will be coming back to your website for more soon.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: