简体   繁体   中英

Getting jquery to work with MVC4

It's not happening. I tried linking the scripts normally in _Layout.cshtml with <script src='@Content.Url("... , installing Web Optimization and using bundles, and putting @Scripts.Render() in the head/body/bottom of _Layout.cshtml and before the <script> tag on the relevant page. What am I missing?

Directory structure

Views
    Shared
        Js
            jquery-1.10.2.js
            jquery.color-2.1.2.min.js

BundleConfig.cs

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Views/Shared/Js/jquery-{version}.js",
        "~/Views/Shared/Js/jquery.color-{version}.js")
    );
}

Global.asax.cs

protected void Application_Start()
{
    // blah, etc, then:
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

_Layout.cshtml

@Scripts.Render("~/bundles/jquery");

I can run the actual javascript/jquery code on JsFiddle, so the validity of what I've written there isn't the problem.

BundleCollection class has IgnoreList property, which contains the patterns of files' names, that will not be rendered. By default it ignores names with min word. You can clear this list inside your RegisterBundles :

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.IgnoreList.Clear();
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Views/Shared/Js/jquery-{version}.js",
        "~/Views/Shared/Js/jquery.color-{version}.js")
    );
}

Got it working: all I did was move the scripts to a different folder, Content/Js , and linked it in via <script src='@Content.Url("... . Content is on the same directory level as Views .

All is well now except that I have no idea why the folder matters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM