Monday, April 2, 2012

How to run Knockout inside MVC 4

I'm watching Knockout Fundamentals by Steve Michelotti

I was having trouble getting the example running that he wrote to show how Knockout is used inside of a MVC 4 project.

This worked for me.

1. Create a new ASP.NET MVC 4 Project using the Internet Application template. Razor view engine is fine.

2. Right click on References and choose "Manage NuGet Packages". Install knockout.js

3. Navigate to Views -> Shared -> _Layout.cshtml
add in script tags:

After this reference, add the knockout reference

The order must be (a) jquery, (b) templates, (c) knockout. Also, the microsoft URL that worked in the previous post does not work in MVC 4 projects. This order must be exact or else it will fail.

4. Go to the scripts directory of the project and create a javascript file, named codeFile.js
Place the javascript code from this jsfiddle link into the javascript file.
JavaScript code from jsFiddle

5. Navigate to Views -> Index.cshtml
Place the html code and the template script tag from the jsfiddle link above into this file.

6. Create a reference to the javascript file by dragging and dropping the javascript file onto the view (Index.chtml).


Eric Veal said...

Good post. I just marginally extended what you wrote. But thanks for the start!!!!

Alex McFerron said...