Tech Junkie Blog: ASP.NET MVC 5 From Scratch : Add JQuery Library Using NuGet

Saturday, June 18, 2016

ASP.NET MVC 5 From Scratch : Add JQuery Library Using NuGet

In the previous blog we've created an empty ASP.NET MVC 5 project.  It's a great starting point but, it's missing a lot things that we will need later.  In this blog we will add JQuery to the empty ASP.NET MVC 5 project that we've just created.

Step-By-Step Instructions:

1. Open the empty ASP.NET MVC 5 project that you've just created

2.  Right click on the the "References" node in the "Solution Explorer", then select "Manage NuGet Packages"

















3. In the search box on the right of NuGet window type "JQuery", the search result will be displayed











4. Click on the "Install" button next to the JQuery result, it should be at the top of the list











5. Once the JQuery library has been installed a green check mark is displayed, click on the "Close" button












6.  Now you should see the JQuery scripts in the "Scripts" folder








7.  To use the JQuery .js script reference the jquery-2.14.min.js file with the following code between the <head> element
<script src="~/Scripts/jquery-2.1.4.min.js"></script>

8. You can use the following code to test if JQuery is working in your ASP.NET MVC project
    <script>
    $(document).ready(alert("jquery is working"));
    </script>

9. So you can modify the "Index.cshtml" to have the following markup to test if JQuery is working or not, if JQuery is working you should get an alert box saying "jquery is working"
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-2.1.4.min.js"></script>
</head>
<body>
    <div>
        Hello World! 
    </div>
    <script>
    $(document).ready(alert("jquery is working"));
    </script>

</body>
</html>


5 comments:

  1. Its recommended that we use Bower Config to for client side dependencies

    ReplyDelete
  2. Thank you for the tutorial, so far works as expected

    ReplyDelete
  3. before running application ,please match the name of the file in script folder with the name in tagging you have added on cshtml view

    ReplyDelete
  4. This is not what I was looking for, but it helped thanks.

    ReplyDelete
  5. I'm not 100% sure but I think you should create bundles in "BundleConfig.cs" and then initialize them in your "_layout.cshtml".


    //create jquery bundle from files that are located in ~/scripts/ and start with jquery-
    bundles.Add(new ScriptBundle("~/bundles/jquery")
    .Include("~/Scripts/jquery-{version}.js"));

    //and then initialize the bundle at the bottom of your layout
    @Scripts.Render("~/bundles/jquery")

    ReplyDelete