Now, I want to tell you How to Resolve Unobtrusive validation on Your ASP.NET 4.5 Apps.
By default, ASP.NET 4.5 has changed the way validation works. On the surface, it works exactly the same as usual, but under the hood, now it uses by default a new kind of unobtrusive validation based in jQuery, instead of the previous default scripts.
Now, the client-side validation is made in a simpler way by using the jQuery validation plugin, and by decorating the different controls with “data-val” attributes, instead of polluting your page with a lot of validation scripts.
For example, this is the resulting HTML for a Requiredvalidator control when you are using the unobtrusive validation mode:
Notice all those “data-val” attributes. By simply inspecting this code you can easily tell how this validation control is behaving. That’s great!
However, if you create a new Empty Web Application using Visual Studio 2012 or later and add a validation control to one page, when you run the app you’ll get this error screen:
“UnobtrusiveValidationMode requires a ScriptResourceMapping for jQuery”
You get this error because the validation scripts search for a script resource called “jquery”, and it’s not present in your app.
You have several options to make it work correctly:
1. Disable the unobtrusive validation on a per-page fashion.
This enables again the former validation system from previous ASP.NET Web Forms versions (up to v.4.0).
Doing this bay hand is tedious if you have more than one or two pages, but is easy. You just need to add this line to the Load event of your page:
Page.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
2. Disable de unobtrusive validation for the whole app.
For achieving this you just need to add one line to our web.config file, under the app.settings node, like this:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
3. Add a ScriptResourceMapping for jQuery, as indicated in the error page.
For achieving this, first you need to download the latest version of jQuery. Download both available editions (the production and development one) and copy those .js files to a “scripts” folder in your app’s root folder.
Now we need to add the Global.asax file to your project. In the Application_Start event you need to define a new ScriptResourceMapping with the name “jquery”, so that the framework knows where to get the jQuery scripts.
This is the needed code in C#:
protected void Application_Start(object sender, EventArgs e)
Path = "~/scripts/jquery-1.8.3.min.js",
DebugPath = "~/scripts/jquery-1.8.3.js",
CdnPath = "http://<a title="ajax" href="#">ajax</a>.aspnetcdn.com/<a title="ajax" href="#">ajax</a>/jQuery/jquery-1.8.3.min.js",
CdnDebugPath = "http://<a title="ajax" href="#">ajax</a>#"
Don’t forget to include a:
at the beginning of the page.