One way of providing good user experience and saving some redundant ‘server side processing’ and ‘bandwidth’ is to use client side validation on the UI. ASP.NET MVC 2 provides for this facility out of the box via the use of **Data Annotations, javascripts and html helpers**. For example say you have an entity Post in your blog application. The recommended ASP.NET MVC 2 approach is to decorate your entity with validation attributes. So for our Post entity we would do the following, assuming you are using Code First Entity Framework 4.0 CTP 4, nHibernate or similar ORM tool.
using System.ComponentModel.DataAnnotations;
public class Post
{
[Required(ErrorMessage = "Title is required.")]
public string Title {get;set;}
[Required(ErrorMessage = "Body is required.")]
public string Body {get;set;}
}
If you are generating your entities using EF4.0 designer tools or similar then you will need to decorate your partial classes, like so.
[MetadataType(typeof(PostMetadata))]
public partial class Post
{
}
public class PostMetadata
{
[Required(ErrorMessage = "Title is required.")]
public string Title {get;set;}
[Required(ErrorMessage = "Body is required.")]
public string Body {get;set;}
}
Then in your ‘view’ you include the required validation javascript files – assuming you have the standard `Scripts` folder that ASP.NET MVC provides for – as follows.
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript" />
<script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript" />
Additionally, you need to include the following call in your view, like so,
<% Html.EnableClientValidation(); %>
..... //Some view codes here
The validation now happens both in the client side via javascript/ajax and also in the server side.