[c#] WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

In my web application I get the following error:

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

How can I solve it?

This question is related to c# asp.net .net validation

The answer is


Since .NET 4.5 the Validators use data-attributes and bounded Javascript to do the validation work, so .NET expects you to add a script reference for jQuery.

There are two possible ways to solve the error:


Disable UnobtrusiveValidationMode:

Add this to web.config:

<configuration>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
</configuration>

It will work as it worked in previous .NET versions and will just add the necessary Javascript to your page to make the validators work, instead of looking for the code in your jQuery file. This is the common solution actually.


Another solution is to register the script:

In Global.asax Application_Start add mapping to your jQuery file path:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition
    {
        Path = "~/scripts/jquery-1.7.2.min.js",
        DebugPath = "~/scripts/jquery-1.7.2.js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
    });
}

Some details from MSDN:

ValidationSettings:UnobtrusiveValidationMode Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

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.

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.


To fix this problem on specific page need to set some validation settings when page loading. Write code below in Page_Load() method:

protected void Page_Load(object sender, EventArgs e)
    {
        ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
    }

Its work for me in .NET 4.5


I think this is the best solution for this type error. So please add below line. Also it work my code when I am using MSVS 2015.

<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>


Jaqen H'ghar is spot-on. A third way is to:

  1. Go to Manage NuGet Packages
  2. Install Microsoft.jQuery.Unobtrusive.Validation
  3. Open Global.asax.cs file and add this code inside the Application_Start method

Code that runs on application startup:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
    Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
    DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});

Further to the accepted answer, I ran into issues with code elsewhere on my site requiring jQuery along with the Migrate Plugin.

When the required mapping is added to Global.asax, when loading a page requiring unobtrusive validation (for example a page with the ChangePassword ASP control), the mapped script resource conflicts with the already-loaded jQuery and migrate scripts.

Adding the migrate plugin as a second mapping solves the issue:

// required for UnobtrusiveValidationMode introduced since ASP.NET 4.5
var jQueryScriptDefinition = new ScriptResourceDefinition
{
    Path = "~/Plugins/Common/jquery-3.3.1.min.js", DebugPath = "~/Plugins/Common/jquery-3.3.1.js", LoadSuccessExpression = "typeof(window.jQuery) !== 'undefined'"
};
var jQueryMigrateScriptDefinition = new ScriptResourceDefinition
{
    Path = "~/Plugins/Common/jquery-migrate-3.0.1.min.js", DebugPath = "~/Plugins/Common/jquery-migrate-3.0.1.js", LoadSuccessExpression = "typeof(window.jQuery) !== 'undefined'"
};
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQueryScriptDefinition);
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQueryMigrateScriptDefinition);

The exception indicates a problem with the unobtrusive JavaScript validation mode. This issue is not Sitefinity specific and occurs in any standard ASP.NET applications when the project targets .NET 4.5 framework and the pre-4.5 validation is not enabled in the web.config file.

Open the web.config file and make sure that there is a ValidationSettings:UnobtrusiveValidationMode in the app settings:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.


Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with asp.net tag:

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Custom Authentication in ASP.Net-Core Custom header to HttpClient request ASP.NET 5 MVC: unable to connect to web server 'IIS Express' IIS Config Error - This configuration section cannot be used at this path Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015 TLS 1.2 in .NET Framework 4.0 The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default Adding ASP.NET MVC5 Identity Authentication to an existing project TypeError: $(...).DataTable is not a function The page cannot be displayed because an internal server error has occurred on server How to get the current logged in user Id in ASP.NET Core When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 No connection could be made because the target machine actively refused it 127.0.0.1 @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How can I validate google reCAPTCHA v2 using javascript/jQuery? How to get DropDownList SelectedValue in Controller in MVC How do I enable NuGet Package Restore in Visual Studio? Specified cast is not valid? Display two fields side by side in a Bootstrap Form variable is not declared it may be inaccessible due to its protection level An unhandled exception occurred during the execution of the current web request. ASP.NET How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception System.web.mvc missing How to get JSON object from Razor Model object in javascript SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance How to get current domain name in ASP.NET How to return a file (FileContentResult) in ASP.NET WebAPI Select query to get data from SQL Server NuGet: 'X' already has a dependency defined for 'Y' How can I make window.showmodaldialog work in chrome 37? Selecting multiple columns with linq query and lambda expression onchange event for html.dropdownlist Pass multiple complex objects to a post/put Web API method How to update a claim in ASP.NET Identity?

Questions with .net tag:

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface How to decode JWT Token? What's the difference between .NET Core, .NET Framework, and Xamarin? .NET Core vs Mono How to specify the port an ASP.NET Core application is hosted on? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests Build error, This project references NuGet IIS Config Error - This configuration section cannot be used at this path There is no argument given that corresponds to the required formal parameter - .NET Error Could not find a part of the path ... bin\roslyn\csc.exe Can you install and run apps built on the .NET framework on a Mac? What is the purpose of nameof? Microsoft.ReportViewer.Common Version=12.0.0.0 What is the default value for Guid? Authentication failed because remote party has closed the transport stream What is the difference between a Shared Project and a Class Library in Visual Studio 2015? How to break out of the IF statement No connection could be made because the target machine actively refused it 127.0.0.1 Default SecurityProtocol in .NET 4.5 How to properly make a http web GET request What is ".NET Core"? IOException: The process cannot access the file 'file path' because it is being used by another process System.web.mvc missing Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation) SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) Write to Windows Application Event Log Operator overloading ==, !=, Equals System.Net.WebException: The remote name could not be resolved: Running multiple async tasks and waiting for them all to complete What is an "index out of range" exception, and how do I fix it? Found conflicts between different versions of the same dependent assembly that could not be resolved Getting the first and last day of a month, using a given DateTime object Error 1053 the service did not respond to the start or control request in a timely fashion BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed Download files from SFTP with SSH.NET library An object reference is required to access a non-static member AppendChild() is not a function javascript Send JSON via POST in C# and Receive the JSON returned? Why is HttpClient BaseAddress not working? KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

Questions with validation tag:

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery How do I turn off the mysql password validation? How to add form validation pattern in Angular 2? Laravel password validation rule Validating Phone Numbers Using Javascript How to validate an e-mail address in swift? javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory' Validate date in dd/mm/yyyy format using JQuery Validate How to properly validate input values with React.JS? Laravel: Validation unique on update How do I make an input field accept only letters in javaScript? Asking the user for input until they give a valid response HTML 5 input type="number" element for floating point numbers on Chrome Laravel update model with unique validation rule for attribute Regex for Mobile Number Validation How can I require at least one checkbox be checked before a form can be submitted? Comparing two input values in a form validation with AngularJS An invalid form control with name='' is not focusable Regex date validation for yyyy-mm-dd How do you do dynamic / dependent drop downs in Google Sheets? How to Call a JS function using OnClick event Javascript Date Validation ( DD/MM/YYYY) & Age Checking Excel data validation with suggestions/autocomplete HTML5 form validation pattern alphanumeric with spaces? HTML5 phone number validation with pattern Implement Validation for WPF TextBoxes How to check if bootstrap modal is open, so I can use jquery validate? jQuery add required to input fields Show red border for all invalid fields after submitting form angularjs Check if input value is empty and display an alert show validation error messages on submit in angularjs How to set HTML5 required attribute in Javascript? Validate phone number using javascript Form Validation With Bootstrap (jQuery) How to check if user input is not an int value How to check if that data already exist in the database during update (Mongoose And Express) Email address validation using ASP.NET MVC data type attributes HTML5 validation when the input type is not "submit" Angularjs prevent form submission when input validation fails HTML/JavaScript: Simple form validation on submit Java Regex to Validate Full Name allow only Spaces and Letters