Search code examples
asp.net-mvcjquery-validateunobtrusive-validation

How Does ASP.NET MVC Load jQuery Validation?


I have a minimal ASP.NET MVC 5 app that was generated via Scaffolding. When I look at the generated _Layout.cshtml file I see a <script> tag toward the bottom of the page that loads jQuery but nowhere in _Layout.cshtm do I see a reference to a jQuery Validation module in a <script> tag.

If I go into Chrome Developer Tools, under the "Sources" tab, I can see that indeed jQuery.validate and jquery.validate.unobtrisuve are loaded! But how can they be loaded if they were not referenced by a <script> tag?


Solution

  • If you look in App_Start BundleConfig.cs you should see reference to:

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*"));
    

    which defines the jQuery validation script bundle. Certain scaffold pages (for example Login) have:

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    

    referenced at the bottom of the View.

    This is picked up by @RenderSection("scripts", required: false) at the bottom of _Layout (which renders the script if it is defined).