Skip to content

Instantly share code, notes, and snippets.

@monoman
Created October 27, 2014 16:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save monoman/ca42e54cdac25ef2284b to your computer and use it in GitHub Desktop.
Save monoman/ca42e54cdac25ef2284b to your computer and use it in GitHub Desktop.
Add to Global.asax.cs and call InitJQuery on Application_Start() to avoid "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'" on migrating to ASP.NET 4.5
private void InitJQuery()
{
string jQueryVersion = JQueryInstalledVersion;
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
Path = "~/Scripts/jquery-" + jQueryVersion + ".min.js",
DebugPath = "~/Scripts/jquery-" + jQueryVersion + ".js",
CdnPath = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + jQueryVersion + ".min.js",
CdnDebugPath = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + jQueryVersion + ".js",
CdnSupportsSecureConnection = true,
LoadSuccessExpression = "window.jQuery"
});
}
private string JQueryInstalledVersion
{
get
{
var scriptsDir = Context.Server.MapPath("~/Scripts/");
foreach (var file in System.IO.Directory.EnumerateFiles(scriptsDir, "jquery-*.min.js")) {
var match = Regex.Match(file, @"(\d+(?:\.\d+){1,3})(\.js)");
if (match.Success) {
return match.Groups[0].Value;
}
}
throw new InvalidOperationException("jQuery is not installed in the ~/Scripts dir");
}
}
Based on **b_levitt** answer to http://stackoverflow.com/questions/16660900/webforms-unobtrusivevalidationmode-requires-a-scriptresourcemapping-for-jquery
But avoiding hardcoding the jQuery version (doesn't play nice with nuget) by using some regex as explained by **Hao Kung** on http://stackoverflow.com/questions/12029161/version-wildcard-in-mvc4-bundle
@manio143
Copy link

If you have jQuery in /Scripts/ but you get the exception you might want to delete '(.js)' in the Regex string.

@KlausKurzawa
Copy link

KlausKurzawa commented Dec 7, 2020

I included 'min.' in the the Regex.match to
var match = Regex.Match(file, @"(\d+(?:\.\d+){1,3})(\.min.js)");
and it worked better for me.

@monoman
Copy link
Author

monoman commented Dec 7, 2020

Thanks @KlausKurzawa, only a nitpick (\.min\.js) instead of (\.min.js)

@mkacena
Copy link

mkacena commented Dec 21, 2023

Thank you for the script, I have used it successfully, just with a minor fix:

The return value of JQueryInstalledVersion property should be: match.Groups[1].Value

match.Groups[0].Value returns version and extension like this: "3.7.1.min.js"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment