Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 88 - Unobtrusive validation in asp.net mvc

Suggested Videos 
Part 85 - Enable client side validation
Part 86 - ValidationSummary in asp.net mvc
Part 87 - What is Unobtrusive JavaScript



Client side validation in asp.net mvc is unobtrusive. To turn on client side validation and unobtrusive JavaScript, make sure the following 2 keys under appSettings element within web.config file are turned on. This will turn on client side validation and unobtrusive JavaScript for the entire application.
<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>



Is it possible to turn these features on/off using code?
Yes, the features can be enabled or disabled in Application_Start() event handler in Global.asax as shown below. This will turn on client side validation and unobtrusive JavaScript for the entire application. 
protected void Application_Start()
{
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
    HtmlHelper.ClientValidationEnabled = true;
}

Is it possible to turn these features on/off for a specific view?
Yes, include the following code, on a view where you want to enable/disable these features.
@{
    Html.EnableClientValidation(true);
    Html.EnableUnobtrusiveJavaScript(true);
}

How is Unobtrusive validation implemented in asp.net mvc?
Using "data" attributes. For example, if we use "Required" attribute, on Name property and if we enable client side validation and unobtrusive JavaScript, then the generated HTML for "Name" field is as shown below.
<input class="text-box single-line" 
      data-val="true" 
      data-val-required="The Name field is required." 
      id="Name" 
      name="Name" 
      type="text" 
      value="Sara Nan" />

data-val=”true”, indicates that the unobtrusive validation is turned on for this element.
data-val-required="The Name field is required.", indicates that the "Name" field is required and the associated error message will be displayed if the validation fails. These data attributes are used by jQuery validation plugin for client side validation.

No comments:

Post a Comment

It would be great if you can help share these free resources