Asp .Net MVC DataAnnotation Compare Attribute

Download Source

In following previous blog posts related to Asp .Net MVC DataAnnotaion, we have looked at how to start building and Asp .Net MVC application from scratch and how DataAnnotaion works.

To continue on our series of Asp .Net MVC validation topic, let's explore another very important [Compare] DataAnnotaion attribute.

Form our previous post, let's go ahead and create couple of new properties on our Asset model class.

Adding Compare Attribute

Also modify our Create view to have input field for this new Property ConfirmAssetTag using appropriate HtmlHelper, as shown in the screen shot below.

EditorFor HtmlHelper

That's pretty much we need to do ,in order to take advantage of DataAnnotaion. Go ahead and run the application. Input some dummy tag number into the AssetTag inpub box and enter something different into the ConfirmAssetTag input box. As soon you as you focus out of the input box you should see an error message appearing next to the ConfirmAssetTag input box.

EditorFor HtmlHelper

Let's also quickly examine how our [Compare] attribute is resulted into when the final HTML was generated by the HtmlHelper.

Data- Attributes

The new [Compare] attribute results into couple of new data-* attributes which are being used by the jQuery Validation and jQuery Unobtrusive Ajax components use to perform the validation before the form is submitted successfully to the server.

Also, following is the result of our ValidationMessageFor HtmlHelper defined inside our view. They are pretty straight forward and very similar to the result of previous example where we used [Required] attribute.

Validation Span data- attributes