Sunday, November 21, 2010

INTEGRATE HTML5 FORM IN ASP.NET MVC

This article is divided into three parts. In the first, part I will show you how you can add Html5 forms in your ASP.NET MVC application with very minimum effort. In the second part, I will show you how to implement client side validation which will trigger automatically even when the browser does not have the html5 client side validation support and in the last part I will show widgetify the form in the client side with jQuery for the older browser that does not have support for Html5 form.
Let’s begin with the server side first. To add Html5 form I will utilize the ModelMetadata and DataAnnotation features that are available in ASP.NET MVC. The DataAnnotation has several attributes which we can use when generating the input types. Let’s say I have a dummy model which is fully decorated with the DataAnnotation attributes:
public class Html5FormModel
{
   [Display(Name = "String", Prompt = "Type a string"), Required]
   public string StringProperty { get; set; }
   [Display(Name = "Decimal", Prompt = "Type a decimal"), Range(1.0, 100.0), Required]
   public decimal? DecimalProperty { get; set; }
   [Display(Name = "Date", Prompt = "Type a date"), DataType(DataType.Date), Required]
   public DateTime? DateProperty { get; set; }
   [Display(Name = "Url", Prompt = "Type an url"), DataType(DataType.Url), Required]
   public string UrlProperty { get; set; }
   [Display(Name = "Email", Prompt = "Type an email"), DataType(DataType.EmailAddress), Required]
   public string EmailProperty { get; set; }
   [Display(Name = "Phone number", Prompt = "Type a phone number"), DataType(DataType.PhoneNumber), Required]
   public string PhoneProperty { get; set; }
}
And I am using the following code to generate the form:
@using (Html.BeginForm()) {
   @Html.ValidationSummary(true, "Validation errors. Please correct the errors and try again.")
   <div>
       <fieldset>
           <legend>Html5 form</legend>
           <div class="editor-label">
               @Html.LabelFor(m => m.StringProperty)
           </div>
           <div class="editor-field">
               @Html.EditorFor(m => m.StringProperty)
               @Html.ValidationMessageFor(m => m.StringProperty)
           </div>
           <div class="editor-label">
               @Html.LabelFor(m => m.DecimalProperty)
           </div>
           <div class="editor-field">
               @Html.EditorFor(m => m.DecimalProperty)
               @Html.ValidationMessageFor(m => m.DecimalProperty)
           </div>

Read more: KAZI MANZUR RASHID'S BLOG part1, Kazi Manzur Rashid Part 2