Friday, June 22, 2012

Northwind-mania: Reading Categories table using MVC 3.0, Entity Framework, and KnockoutJS

This lesson demonstrates how one can easily display the contents of the Categories table in the Northwind database on a web page using KnockoutJS:


  • Visual Studio 2010
  • MVC 3.0
  • Northwind database
  • SQL Server Express
  • NuGet

Step 1:

In Visual Studio click: File >> New Project. On the next dialog choose: Web >> ASP.NET MVC 3.0 web application and give your application a decent name as shown below:


Step 2:

On the next screen, choose “Internet Application”.


Step 3:

In Solution Explorer, right-click on Reference and select “Manage NuGet Packages …”.


Step 4:

Enter “knockout” in the search field on the top right-hand-side of the next screen. Select “knockoutjs” then click on the “Install” button.


The knockoutjs JavaScript file will be contained in your project in the Scripts directory:


Step 5:

Right-click on the “Models” folder: Add >> New Item:


Add an “ADO.NET Entity Data Model (Visual C#)” item named “NorthwindModel.edmx”:


Select “Generate from database” then click “Next”.


Choose the appropriate Northwind database connection then click Next.


Click on the checkbox beside Tables, then click the “Finish” button.


Step 6:

Replace the Index() action in the HomeController.cs with the following code:

public ActionResult Index() {
   using (NorthwindEntities ctx = new NorthwindEntities()) {
       var categories = from c in ctx.Categories
                        select new { c.CategoryID, c.CategoryName };

       ViewBag.Categories = categories.ToList();

       return View();

Step 7:

Open the index.cshtml file in the Views/Home directory. Drag and drop the “knockout-2.1.0.js” from the Scripts folder into the index.cshtml file above the <h2> tag. This produces the <script> tag pointing to the JavaScript file.

Step 8:

Replace the contents of the <p>..</p> section with the following:

<ul data-bind="foreach: categories">    
    <li><span data-bind="text: $data.CategoryName"></span></li>
<script type="text/javascript">   
    var viewModel = {        
        categories: @Html.Raw(Json.Encode(ViewBag.Categories))    

Step 9:

Run the application by hitting F5. You should see the following web page:


If you look at the page view source, you should notice the following JSON data in the <script> section:

<script type="text/javascript">   
  var viewModel = {        
      categories: [
         {"CategoryID":4,"CategoryName":"Dairy Products"},

No comments:

Post a Comment