ASP.NET MVC 5 Tutorial :: Add KnockoutJs to Project With NuGet

KnockoutJs JavaScript library to MvcApp project. KnockoutJs is a great lightweight data binding library. Follow the steps below to add KnockoutJs to your ASP.NET MVC project.

Step-By-Step Instructions:

1. Right-click on the project’s “References” node, then select “Manage NuGet Packages”

ko-1

2. In right hand side type in “knockoutjs”, then click on the “Install” button next to the knockoutjs package

ko-2

3.  You should see a green checkmark after you finished adding the knockoutjs library to the MvcApp project.

ko-3

4. In the “Scripts” folder you will see the knockout JavaScript files

ko-6

5. Now that we have the knockoutjs files we need to add the files to the BundleConfig.cs file to register them

6. Open the BundleConfig.cs file in the “App_Start” folder type the following lines of code inside the RegisterBundles method, this tells MVC to include any files in the “Scripts” folder that starts with the string “knockout”

bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout*"));

BundleTable.EnableOptimizations = false;
bundles.UseCdn = true;

The entire code looks like the following up to this point in our project.

using System.Web;
using System.Web.Optimization;

namespace MvcApp
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js").Include("~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/bootstrap","https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js").Include("~/Scripts/bootstrap.js","~/Scripts/respond.js"));

bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout*"));

bundles.Add(new StyleBundle("~/Content/bootstrap", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css").Include("~/Content/bootstrap.css"));

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/Styles.css"));

BundleTable.EnableOptimizations = false;
bundles.UseCdn = true;
}
}
}

7. In the “Views” → “Shared” folder, open the “_Layout.cshtml” file and add the following code

ko-8

@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/knockout")

If you press Ctrl+F5 to run the application and look at the browser source code you will see that the knockout js files have been added to the page

ko-9

Posted in Hosting News.