简体   繁体   中英

Why do i have to include JS files in order to work with jquery in every single view?

As the question says all about it but to give you a little more information i included all the .js files in my Asp.NET Mvc application like below:

<script src="~/Scripts/jquery-1.10.2.js"></script>

Even that I have to include .js files in every single page in order to be able to work with jQuery else it doesn't work. I tried to include these script files in BundleConfig surprisingly the scripts where not working at all even on the layout page. What is the trick?!

In general you have got an App_Start/BundleConfig.cs in your project

public class BundleConfig
{
    public static readonly string SiteJquery1Bundle = "~/bundles/jquery1";
    public static readonly string SiteJquery2Bundle = "~/bundles/jquery2";

    public static void RegisterBundles(BundleCollection bundles)
    {
        // We will choose bundle to render depending on IE version in view
        bundles.Add(new Bundle(SiteJquery1Bundle)
               .Include("~/Scripts/jquery-1.10.2.js"));
        bundles.Add(new Bundle(SiteJquery2Bundle)
               .Include("~/Scripts/jquery-2.1.3.min.js"));

    }

In your Shared/_Layout.cshtml view add:

<html>
<head>
<title>...</title>
<!--[if lt IE 9]>
@Scripts.Render(BundleConfig.SiteJquery1Bundle)
<![endif]-->
<!--[if gte IE 9]><!-->
@Scripts.Render(BundleConfig.SiteJquery2Bundle)
<!--<![endif]-->
...
</head>

So, default ASP.NET MVC projects adds _ViewStart.cshtml which defines single layout in every view. And check bundle registration in Global.asax.cs

protected void Application_Start()
{
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

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