This lesson demonstrates how one can easily display the contents of the Categories table in the Northwind database on a web page using KnockoutJS:
Pre-requisites:
- 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>
</ul>
<script type="text/javascript">
var viewModel = {
categories: @Html.Raw(Json.Encode(ViewBag.Categories))
};
ko.applyBindings(viewModel);
</script>
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":1,"CategoryName":"Beverages"},
{"CategoryID":2,"CategoryName":"Condiments"},
{"CategoryID":3,"CategoryName":"Confections"},
{"CategoryID":4,"CategoryName":"Dairy Products"},
{"CategoryID":5,"CategoryName":"Grains/Cereals"},
{"CategoryID":6,"CategoryName":"Meat/Poultry"},
{"CategoryID":7,"CategoryName":"Produce"},
{"CategoryID":8,"CategoryName":"Seafood"}
]
};
ko.applyBindings(viewModel);
</script>
No comments:
Post a Comment