Tuesday, 16 December 2014

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Example scenario when you might stumble across this error
When your creating a web application which utilizes the jquery framework and is targeted against .NET 4.5 framework (I.e. When httpRuntime targetFramework is set to 4.5 in your config).

What is jQuery Unobtrusive Validation?
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML. You can then read the validation even in the HTML source.

With the unobtrusive way:

You don't have to call the validate() method.
You specify requirements using data attributes (data-val, data-val-required, etc.)

Jquery Validate Example:

Code Snippet
  1. <input type="text" name="email" class="required">
  2.         $(function () {
  3.             $("form").validate();
  4.         });
End of Code Snippet

Jquery Validate Unobtrusive Example:

Code Snippet
  1. <input type="text" name="email" data-val="true"
  2. data-val-required="This field is required.">  
  4. <div class="validation-summary-valid" data-valmsg-summary="true">
  5.     <ul><li style="display:none"></li></ul>
  6. </div>
End of Code Snippet

How to use jQuery Unobtrusive Validation and FIX the issue
You can fix this problem by registering jQuery in Global.asax in the Application_Start event. Be sure to replace the jquery version with your particular version!

Code Snippet
  1. ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
  2.     new ScriptResourceDefinition
  3. {
  4. Path = "~/scripts/jquery-1.7.2.min.js",
  5. DebugPath = "~/scripts/jquery-1.7.2.min.js",
  6. CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
  7. CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
  8. });
End of Code Snippet

How to disable jQuery Unobtrusive Validation
Add this code snippet to your web.config file. If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. However, If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.
Code Snippet
  1. <appSettings>
  2.      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  3. </appSettings>
End of Code Snippet

No comments: