Knockout in MVC4

In this article I am trying to elaborate the concept of Knockout JavaScript library with a demo application in MVC4, This is my first article about knockout.


Knockout is a JavaScript library that allows us to bind html elements against any data model. Knockout is use with both server side as well as client side technology; it is compatible with all types of technologies. It provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM (UI) and any changes to the DOM are automatically reflected to the data model.

Getting start: -

1.       Create an Empty MVC4 project on visual studio with appropriate name.

2.       Add a Controller with below line of code.

public ActionResult Index()


   Book book = new Book();

   book.BookId = "B101";

   book.BookName = "Two States";

   book.BookAuthor = "Chetan Bhagat";

   return View(book);


3.       Add a strongly type View with @using System.Web.Script.Serialization; @model MvcApplication20.Models.Book 

@using System.Web.Script.Serialization;

@model MvcApplication20.Models.Book 


    ViewBag.Title = "Index";

    Layout = "~/Views/ViewPage1.cshtml";



<script src="~/Scripts/knockout-2.1.0.js"></script>

<script src="~/Scripts/knockout.mapping-latest.js"></script>



        <td>Book ID:</td>

        <td><strong data-bind="text: BookId"></strong></td>



        <td>Book Name:</td>

        <td><strong data-bind="text: BookName"></strong></td>




        <td><strong data-bind="text: BookAuthor"></strong></td>




<script type="text/javascript">



          var model = @Html.Raw(Json.Encode(Model))       





4.       Add a Class in Model folder with Book.cs named.

public class Book


   public string BookId { get; set; }

   public string BookName { get; set; }

   public string BookAuthor { get; set; }


5.       Add a folder with Script name in your project in solution explorer and add below scripts.

a.       knockout-2.1.0.js

b.      knockout.mapping-latest.js

Output: -


Knockout in MVC4

  Modified On Nov-29-2017 05:19:38 AM

Leave Comment