Advertise with us

Getting start with KnockoutJS in ASP.NET MVC 4

Hi everyone in this article I’m explaining about knockoutjs with mvc 4 for beginners.


Here I am going to explain, how to use knockout js with ASP.NET MVC 4 application and a basic JavaScript pattern that helps us to write a more maintainable code. The example which I use here is most suitable for single-page application.  However, it is not limited to this, you can use it in any ASP.NET MVC application according to your needs. 


If we are working with ASP.NET MVC framework, then its obvious that we need to work much on JavaScript (I can say jQuery, since we can see this in almost every project). According to my experience, for a traditional ASP.NET developer working with JavaScript is always a nightmare. Also, it was really scary that there is no server-side controls and no viewstate in MVC application. Well, once I started to work in MVC application I explored JavaScript more along with jQuery and found it extremely easy and solid framework for web development. Most of my recent projects were implemented as a single-page application. There by implementing whole UI stuffs using JavaScript, jQuery, jQuery-UI, knockout and some other js libraries. Initial times I phased lot of issues though, now I'm really feeling very comfortable with the framework and love this approach. I would like to say many thanks to Douglas Crockford for his fantastic book JavaScript Good Parts, which helped me a lot to understand JavaScript better. 

Setup the Project:

 Start Visual Studio >> File >> New Project >> ASP.NET MVC 4 Web Application


Getting start with KnockoutJS in ASP.NET MVC 4

Give the application name and click ok

After click ok one window open like this and you select the “Basic” project type.

Getting start with KnockoutJS in ASP.NET MVC 4

We need to select the view engine for the ASP.Net mvc application. Select "Razor view engine".

After selecting the project type, the ASP.Net MVC4 application project structure will be created for the Basic project type.

We won't have any of the views except layout and viewstart since we have selected a Basic type. So we need to create an index view as well as controller for the same.


Right click on view >> Add >> New Folder


Getting start with KnockoutJS in ASP.NET MVC 4


Give the folder name “Home” and add an Index view for our application as shown in the preceding image. 

Getting start with KnockoutJS in ASP.NET MVC 4


If you follow the preceding shown steps then a dialog box will be displayed to name the view, type the name "Index" for the view and click "Ok". Leave the other option as it is.

To render the views, we need the controller. So let us create a controller as shown in the following figure.

Getting start with KnockoutJS in ASP.NET MVC 4

As we know, the naming convention is followed for creating folders, views and controllers, just follow it. While creating the controller, select the scaffold option to add the default MVC read/write/delete actions.

Now our project structure is proper. Let us check for the existence of a necessary JavaScript framework like jQuery, Knockoutjs,. and so on. Double-check that latest the Knockout framework script files are added to the Scripts folder. If not then use NuGet Manager and add it to the script folder.

As a feature of ASP.Net MVC4, we need to bundle the JavaScript and CSS files. By default, the jQuery framework will be bundled. For KnockoutJS, we need to add the Knockoutjs file to bundle.

Since we have enabled the Bundling feature, if you want to debug the script, it will be daunting because the MVC framework minifies the scripts and CSS by default.

<compilation debug="true" targetFramework="4.5" />

The code above will make it easier to debug the scripts.

We are ready to use KnockoutJS with ASP.Net MVC4. Let us see the Model, controller and view in details.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace KnockoutJsSample.Models
    public class Student
        public string Name { get; set; }
        public string ContactNo { get; set; }
        public string City { get; set; }
        public int Age { get; set; }


The Home controller has an action called Index. When you type http://localhost:1981/Home/Index in the address bar, the control goes to the Home controller and it will look for an Index action.

using KnockoutJsSample.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace KnockoutJsSample.Controllers
    public class HomeController : Controller
        // GET: /Home/
        public static Student _data = new Student()
            Name = "Kamlakar Singh",
            ContactNo = "1212121212",
            City = "Allahabad",
            Age = 23
        public ActionResult Index()
            return View();
        public ActionResult TestJson()
            return Json(new {
                ContactNo = "1212121212",
                City = "Allahabad",
                Age = 24
        public JsonResult GetStudent()
            return Json(_data,JsonRequestBehavior.AllowGet);
        public JsonResult UpdateStudent()
            string jsonString = Request.Form[0];
            Student student = JsonConvert.DeserializeObject<Student>(jsonString);
            _data.Name = student.Name;
            _data.ContactNo = student.ContactNo;
            _data.City = student.City;
            _data.Age = student.Age;
            return Json(_data);

As you see in the code above, the Index action returns the View "Index" as an Action Result and it will be rendered in the document.


The Index view's markup is given below.

    ViewBag.Title = "Index";
    Layout = null;
        <input data-bind='value: displayName' /></p>
        <input data-bind='value: displayAge' /></p>
    <p>Name Age:
        <input data-bind='value: displayNameAge' /></p>
    <button data-bind='click: loadFromServer'>Load From Server</button>
    <p>Input Name:
        <input data-bind='value: inputName' /></p>
    <p>Input Age:
        <input data-bind='value: inputAge' /></p>
    <button data-bind='click: updateLocal'>Update Local</button>
    <button data-bind='click: updateServer'>Update Server</button>
    <h2>KO Content</h2>
    <pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script type="text/javascript">
    var PersonViewModel = function (name, age) {
        var self = this;
        self.displayName = ko.observable(name);
        self.displayAge = ko.observable(age);
        self.displayNameAge = ko.computed(function () {
            return self.displayName() + " age " + self.displayAge();
        }, self);
        self.inputName = ko.observable("Pankaj");
        self.inputAge = ko.observable("15");
        self.updateLocal = function () {
        self.loadFromServer = function () {
            $.getJSON("/home/GetStudent", function (data) {
        self.updateServer = function () {
            var data = "{ \"name\" : \"" + self.inputName() +
              "\", \"age\" : \"" + self.inputAge() + "\"}";
            $.post("/home/UpdateStudent", data, function (returnedData) {
            }, "json");
        self.updateThis = function (jsonData) {
            var jsonString = JSON.stringify(jsonData);
            var parsed = JSON.parse(jsonString);
    var myViewModel = new PersonViewModel("Kamlakar", "21");
    ko.applyBindings(myViewModel); // This makes Knockout get to work

When the call is made to the Index action of the Home controller, first the Index.cshtml will be loaded into _Layout.cshtml and _Layout.cshtml will be loaded into the _ViewStart.cshtml and the _ViewStart.cshtml will be rendered into document.

Once the entire document is ready, the jquery's ready callback will be executed for binding the Knockout view model to MVC view.

In this article's example, we are displaying a welcome text with animation. This is over first on KnockoutJS with ASP.Net MVC4 so we had a simple binding example.

In my next post i'll explain about Crud Operations Using Generic Repository Pattern in ASP.NET MVC 4.

Last updated:9/7/2019 12:15:09 AM
Kamlakar Singh

Kamlakar Singh

software engineer


Leave Comment