Home > DeveloperSection > Articles > Knockout in MVC4

Knockout in MVC4


ASP.NET MVC ASP.NET MVC 
Ratings:
2 Comment(s)
 3246  View(s)
Rate this:

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

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";

}

<h2>Book</h2>

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

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

<table>

    <tr>

        <td>Book ID:</td>

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

    </tr>

    <tr>

        <td>Book Name:</td>

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

    </tr>

    <tr>

        <td>Author:</td>

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

    </tr>

</table>

 

<script type="text/javascript">

     $(function()

     {

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

          ko.applyBindings(model);

     });

</script>

 

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


Nice article

By Johnny Depp on   3 years ago
Nice article

Good article

By Johnny Depp on   3 years ago
Good article

Don't want to miss updates? Please click the below button!

Follow MindStick