We can enable or disable the client side validations in MVC4 by doing simple configuration / code changes.
For enable / disable validations application level:
We can use any one of the below two methods (web.config change or Global.asax.cs change)
Configuration change in web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Code change in Global.asax.cs file
protected void Application_Start()
{
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}
For enable/disable validation in a particular view
set the below two properties in the View Razor code.
@{
ViewBag.Title = "Index";
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}
Note:
In addition to the above changes for enable the client side validations we need to add the JQuery, jquery.validate, jquery.validate.unobtrusive js file reference in bundleconfig.cs and we have to consume them in the view.
Ex:
BundleConfig.config:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
}
In View Razor code at bottom:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
Ref: http://www.dotnetlearners.com/blogs/view/86/Enable-or-disable-client-side-validations-in-mvc4.aspx
Comments
Post a Comment