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:
http://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js

After this reference, add the knockout reference
"~/Scripts/knockout.js"

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).
src="../../Scripts/codeFile.js"

2 comments:

Eric Veal said...

Good post. I just marginally extended what you wrote. But thanks for the start!!!! http://kickmajorbooty.blogspot.com/2012/06/scenario-1-getting-mvc-40-release.html

Alex McFerron said...

cool!