articles

Home / DeveloperSection / Articles / Getting start with KnockoutJS in ASP.NET MVC 4

Getting start with KnockoutJS in ASP.NET MVC 4

Anonymous User8937 30-Jan-2015

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

Description:

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. 

Background:

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.

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace KnockoutJsSample.Models
{
    publicclassStudent
    {
        publicstring Name { get; set; }
        publicstring ContactNo { get; set; }
        publicstring City { get; set; }
        publicint Age { get; set; }
    }
}


Controller


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
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicstaticStudent _data = newStudent()
        {
            Name = "Kamlakar Singh",
            ContactNo = "1212121212",
            City = "Allahabad",
            Age = 23
        };
        publicActionResult Index()
        {
            return View();
        }
        publicActionResult TestJson()
        {
            return Json(new {
                Name="Rohit",
                ContactNo = "1212121212",
                City = "Allahabad",
                Age = 24
            },JsonRequestBehavior.AllowGet);
        }
        publicJsonResult GetStudent()
        {
            return Json(_data,JsonRequestBehavior.AllowGet);
        }
 
        [HttpPost]
        publicJsonResult 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.

View

The Index view's markup is given below.

@{
    ViewBag.Title = "Index";
    Layout = null;
}
 
<h2>Index</h2>
 
<div>
    <p>Name:
        <inputdata-bind='value: displayName'/></p>
    <p>Age:
        <inputdata-bind='value: displayAge'/></p>
    <p>Name Age:
        <inputdata-bind='value: displayNameAge'/></p>
    <buttondata-bind='click: loadFromServer'>Load From Server</button>
</div>
 
<div>
    <h2>Input</h2>
    <p>Input Name:
        <inputdata-bind='value: inputName'/></p>
    <p>Input Age:
        <inputdata-bind='value: inputAge'/></p>
    <buttondata-bind='click: updateLocal'>Update Local</button>
    <buttondata-bind='click: updateServer'>Update Server</button>
</div>
 
<div>
    <h2>KO Content</h2>
    <predata-bind="text: ko.toJSON($root, null, 2)"></pre>
</div>
 
<scriptsrc="~/Scripts/jquery-1.7.1.min.js"></script>
<scriptsrc="~/Scripts/knockout-2.1.0.js"></script>
 
<scripttype="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.displayName(self.inputName());
            self.displayAge(self.inputAge());
        };
 
        self.loadFromServer = function () {
            $.getJSON("/home/GetStudent", function (data) {
                self.updateThis(data);
            });
        };
 
        self.updateServer = function () {
            var data = "{ \"name\" : \"" + self.inputName() +
              "\", \"age\" : \"" + self.inputAge() + "\"}";
            console.log(data);
            $.post("/home/UpdateStudent", data, function (returnedData) {
                self.updateThis(returnedData);
            }, "json");
        };
 
        self.updateThis = function (jsonData) {
            var jsonString = JSON.stringify(jsonData);
            var parsed = JSON.parse(jsonString);
            self.displayName(parsed.Name);
            self.displayAge(parsed.Age);
        };
    };
    var myViewModel = new PersonViewModel("Kamlakar", "21");
    ko.applyBindings(myViewModel); // This makes Knockout get to work
</script>

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.


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By