如何在 jquery 验证后呈现我的脚本(使用 Bundle Config)

How to render my script after jquery validate (using Bundle Config)

我想使用验证器来验证我的表单。

捆绑包配置:

public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

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

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js",
                       "~/Scripts/script.js" // here I'm using jquery validate.
                      ));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }

Layout.cshtml

@Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

错误:

Uncaught TypeError: $(...).validate is not a function at HTMLDocument. (script.js:4) at fire (jquery-1.10.2.js:3062) at Object.fireWith [as resolveWith] (jquery-1.10.2.js:3174) at Function.ready (jquery-1.10.2.js:447) at HTMLDocument.completed (jquery-1.10.2.js:118)

我脚本中的代码:

var loginValidator = $("#loginForm").validate({...

它首先呈现 jquery、验证器,最后呈现我的脚本。 为什么找不到验证器?

预先感谢您的回复!

您没有将 jQuery 验证包包含到您的布局中,因此未加载它。

尝试以下布局代码:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

注意 jQuery validate 应该在 jQuery 之后加载。