Asp .Net MVC DataAnnotation Required Attribute

Facebook Twitter Google Digg Reddit LinkedIn Pinterest StumbleUpon Email
Download Source

Validation is a key part of any web application we build. Building web applications with Asp .Net MVC Framework has a lot of benefits and one of them is validation using DataAnnotation.

In this blog post we will go through the basics of DataAnnotaiton and see how this can make our life easier while working with data validations. DataAnnotaiton works with other two components to provide us a robust client side validation. These components are

Following are some of the attributes available out of the box in System.ComponentModel.DataAnnotations Namespace.

  • Required
  • Compare
  • Display
  • Range

The [Required] DataAnnotation Attribute

This is the most commonly used and easiest to understand attribute of all. As the name suggests, when you want to make an input field required just decorate that Property in your C# class with [Required] attribute and everything else will be done auto-magically.

To continue reading further you will need the a basic MVC 4 application. If you are new to MVC 4 and not sure from where to start please refer to this blog post. It describes a step by step process to create an empty Asp .Net MVC application.

Once you follow along that post you should have a pretty clean Asp .Net MVC application built from scratch. Now, let's go ahead and add a new Controller AssetController. To examine the DataAnnotation we will be creating an imaginary Asset Management Application and the screen to enter Asset details.

Adding Controller

Adding Controller

Go ahead and add a new Model class in your MVC application under the Model folder.

Adding Model

Naming  Model Class

Next, define three properties in your Asset class as describe below. I have also decorated two of these properties with [Required] attribute. For this you will have to add the following using statement in your class.

using System.ComponentModel.DataAnnotations;

 
    public class Asset
    {
        public int AssetID
        { get; set; }

        [Required]
        public string AssetName
        { get; set; }

        [Required]
        public string AssetTag
        { get; set; }    
    }

Now we will add a new ActionMethod and a respective View as shown in the following screens.

Adding Model

Naming  Model Class

We are using the Scaffolding feature of MVC and utilizing Create template to generate the view for us. Let's go ahead and refer our jQuery Validation bundle in the script section. Next we wan to make a small change in our Route configuration to default to AssetController and Create ActionMethod. You can do this by making following changes in your RouteConfig.cs file under App_Start folder.

Changing Route Configuration

Go ahead and run the application. The application should default to Create Asset page. Without passing any data, just hit the "Create" button and you should see validation messages similar to following screen shots.

Running The Application

Understanding how it works

When we used the [Required] DataAnntation attribute and created our Views using Asp .Net MVC HtmlHelper methods ,on the client machine, it appended some extra data-* attributes on our input tag. To Learn more about data-* attribute refer to this blog post.

HtmlHelper EditorFor

has resulted into,

Data-* Attributes

When we use these HtmlHelpers, before rendering HTML output to the browsers, they examine the DataAnnotation attributes and based on the attribute it will append extra data-* attributes. In our case we are using the [Required] attribute and it is resulting into,

  1. data-val="true" : It means that this field must have a value
  2. data-val-required = "The.." : What validation message to display when the above condition is not matched

HtmlHelper ValidationMessageFor

And the ValidationMessageFor has resulted into,

Data-* Attributes

  • data-valmsg-for="AssetName" : Which field's error message has to be displayed in this field.

With this parameters in hand, the jQuery unobtrusive validation plug-in will run before the form submit and check for any input whose data-val is set to true. And if it finds the one without values it knows what to do based on the rest of the data-* attributes.

In, the next few blog posts we will continue looking into other DataAnnotation Attributes.