Include jQuery Library In A View Or Page In Different Ways

How to include jQuery in an ASP.NET page

For adding a jQuery library reference to an ASP.Net page, you just need to specify the source of the library in the script tag.

If you are referencing a library from the project folder,

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

If you are referencing the library from a CDN (Content Delivery Network),

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.10.2.js" type="text/javascript"></script>  

The above line will include the jQuery library form the Microsoft CDN.

How to include jQuery in an MVC View

You can do this in different ways.

Direct referencing in page/view

If you are not using any layouts for your Views, simply include the reference of the library in the View.

If you are referencing a library in a Razor View from the project folder.

<script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>  

If you are referencing the library from Microsoft CDN.

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.10.2.js" type="text/javascript"></script>  

Bundling

We use bundling for better performance. Let’s see how to include it when you use bundling.

There is a BundleConfig.cs file in your project’s App_Start folder. Add the below line of code in your BundleConfig class.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));  

Normally, that line is added when you create the project; if not, add it.

The above line of code will do three things:

  1. Will create a bundle with name ~/bundles/jquery.
  2. Will include the latest version of the jQuery library from your project’s folder.
  3. Bundler is smart enough to include the .js file if the application is running in Debug mode and the .min.js file if the application is runnig in the Release mode.

Using CDN

If you want to use the library from a CDN, use the below code.
bundles.UseCdn = true;  
bundles.Add(new ScriptBundle("~/bundles/jquery", @ "//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.js").Include("~/Scripts/jquery-{version}.js")); 

The above code will do the below things.

  1. Will create a bundle with name ~/bundles/jquery.
  2. Will include the latest version of the jQuery library from the Microsoft CDN while in Release mode.
  3. Will include the latest version of the jQuery library from your project’s folder while in Debug mode.

Finally, use the @Scripts.Render to include the bundle in your Razor View. While using CDN, you should have a fallback mechanism in case the library is not loaded due to some network issues.

@model BundlesDemo.Models.WeightStatus  
@{  
    Layout = null;  
}  
<!DOCTYPE html>  
<html>  
  
<head>  
    <title>Index</title>  
</head>  
  
<body>  
    <div>  
        <p> Welcome to Bundles Demo Home View! </p>  
    </div>  
</body>
@Scripts.Render("~/bundles/jquery")
<scripts type="text/javascript">
   if (typeof jQuery == 'undefined') {
      var jql = document.createElement('script');
      jql.src = '@Url.Content("~/Scripts/jquery-1.10.2.js")';
      jql.type = 'text/javascript';
      document.getElementsByTagName("head")[0].appendChild(jql);
   }
</scripts>
</html> 

Another way of doing this is, add the below code to your page's <head> tag:

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.js"></script>
<script>
window.jQuery || document.write('<script src="~/Scripts/jquery-1.10.2.js"><\/script>');
</script>

How to Use Bundling with Layout

If you have many Views which have a common layout, you will normally use layouts.

Adding Layout file to your project

By default, a _Layout.cshtml page will be created when you create an MVC project. If not created, create one.

Right-click on Shared folder, Add -> New Item -> Layout Page.

jQuery

You can add your common functionality in the layout page.

Advantage of using bundling with layout

If you are using layout, you can include your bundle (render bundle) in your layout.

The benefit of this approach is, you don’t have to use the @Scripts.Render in all the Views where you use the particular layout which already includes the @Scripts.Render section.

Adding jQuery library or file to Layout page

Add the @Scripts.Render section at the end of the layout page. You can render these all the bundles that you want to use in your layout.

<!DOCTYPE html>  
<html>  
  
<head>  
    <meta charset="utf-8" />  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>@ViewBag.Title - My Bundles Demo Application</title> @Styles.Render("~/Content/css") </head>  
  
<body>  
    <p> Bundles Demo Application Is to Demonstrate the Use and Advantages of Bundling. </p>  
    <div class="container body-content"> @RenderBody()  
        <hr />  
        <footer>  
            <p>© @DateTime.Now.Year - My Bundles Demo Application</p>  
        </footer>  
    </div> 
@Scripts.Render("~/bundles/jquery") 
@Scripts.Render("~/bundles/bootstrap") 
@RenderSection("scripts", false) </body>  
  
</html>  

Adding <script> element to view or page

After including the jQuery libraries, we may need to use some jQuery scripts in the page like below:

<script>  
    $(document).ready(function() {  
        alert("Hey! I am ready");  
    });  
</script>  

We will define a scripts section in the Layout like we have done in the Layout page code above.

@RenderSection("scripts", false)

Or

@RenderSection("scripts", required: false)

The second parameter in the RenderSection tells that this section is not mandatory in the View where the layout is included, otherwise, the section is mandatory.

Adding Layout to View

Now, go to the View where we include the _Layout.cshtml.

Add the below line of code to include the layout in your View.

@{  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  

Define scripts section

In the View, you need to define the scripts section and use your <script></script> element inside the section.

@model BundlesDemo.Models.WeightStatus  
@ {  
    ViewBag.Title = "Home Page";  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  
@section scripts { < script > $(document).ready(function() {  
        alert("Hey! I am ready ");  
    }); < /script>  
}  

ViewStart

The above use _Layout has one disadvantage. We need to include the layout in all the Views where we want to include the layout.

_ViewStart.cshtml was introduced in MVC3 to overcome this issue. It is placed in the Views folder. It is designed to give common functionality to all the Views under the folder and sub folders where the _ViewStart.cshtml is present.

In my Bundles Demo project,

jQuery

All the Views inside Views folder including the one in Home folder will get the layout mentioned in the _ViewStart.cshtml.

You can have multiple _ViewStart.cshtml files in differenct folders, if you want to enforce different styles for different folders.

Apply Layout using _ViewStart.cshtml

_ViewStart.cshtml is Layout file which allows writing codes.

All you need to do is to specify the path of the Layout file to apply the layout, as below.

@ {  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  

Conditionally load Layout pages using ViewStart

Since _ViewStart.cshtml allow codes to be written apart from the _Layout file path, we can use it to conditionally change the layout of the View.

Some practical scenarios are,

  • Different layout for the user, say for admin and normal user.
  • Different layout based on device, say for desktop and mobile.
@ {  
    if (User.IsInRole("admin")) {  
        Layout = "~/Views/Shared/_AdminLayout.cshtml";  
    } else {  
        Layout = "~/Views/Shared/_UserLayout.cshtml";  
    }  
} 

Thank you for reading!


Similar Articles