Saturday, May 10, 2014

Working with Knockoutjs in MVC5 C# - Introduction

     Knockout is a JavaScript library that easy to create rich, responsive and editor user interfaces with a clean underlying data model. The context of UI changes dynamically. And it is more simple and maintainably. KO is built on Model View ViewModel (MVVM). MVVM is a specific implementation targeted at UI development platforms which support the event-driven programming in Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages.
   The main features of KO are automatic UI change when data model update, declarative bindings and trivially extensible.

  • KO is free and open source.
  • KO is a pure JavaScript library. It works with any server or client-side technology.
  • It supports event-driven programming language.
  • Easily create complex dynamic user model.
  • It supports all mainstream browsers (IE , Firefox, Chrome, Safari and others).
  • It is very compact in size.
  • UI dynamically changes when user model updated.


Observable:  It is used to declare your model properties. Whenever the property is updated with UI and new value then the property dependencies will automatically changes the UI and new value.

Ex:   this.userName = ko.observable("Prakash");

ObservableArray: This is used to bind with the List or array data. If you are displaying or editing  multiple values then you can use it. It has more functions like push, pop, shift, unshift, reverse, sort, splice. For info visit:

Ex:  this.users = ko.observableArray(); //empty array
       this.users = ko.observableArray([    //with data
       {name="Prakash", group="IT"},
       {name="Ram", group="CSE"},
       {name="Raj", group="EEE"},
       {name="Teja", group="ME"}

Computed: It is used to computed two or more observables into one. You can join the two observables, make calculation for observables like percentages, age.

Ex:  function viewModel = {
      this.userFirstName = ko.observable("Tej");
      this.userLastName = ko.observable("Prakash");
        this.userFullName =ko.computed(function() {
          return this.userFirstName() + " " + this.userLastName();      // result: Tej Prakash

 The 'data-bind' attribute will detects the changes and update the view automatically. The main advantage is no need to change the view. There are many bindings for handling text, arrays and forms.

The most useful bindings.

text: It is used to display the text value of your parameter.
          Ex:  Fill the value in ViewModel
               this.UserName=observable("Teja prakash");
                then we can use it in view like below                        
             <span data-bind="text: UserName"></span>

visible: It helps you to enable or disable the UI element based upon the value passed to it's bindings.
         Ex: Fill the value in ViewModel
                this.NewDiv=observable(True);    // To unhide the DIV
                this.NewDiv=observable(False);   // To hides the DIV

                then we can use it in view like below                        
             <div data-bind="visible: NewDiv">
                 Create new account!!!!

foreach: It is used for looping over the array. This is especially useful for rendering lists or tables.
         Ex:  <table>
                     <tr><th>User Id</th>
                 <tbody data-bind="foreach: users">     // Looping array!!
                   <td data-bind="text: userId"></td>
                   <td data-bind="text: name"></td>

If/Ifnot: It is used to check the values only when if a specified condition true or false.
         Ex: <div data-bind="If: !Users()"> No users found </div>

click: It represents a click event handler added to the UI element so that JavaScript is called.
         Ex: <button  data-bind="click: $root.createUser" title="Save">Save</button>

value: It links with the UI's element value with the property on your viewModel.When the user edits the value in the associated form control, it updates the value on your view model. Likewise, when you update the value in your view model, this updates the value of the form control on screen.
         Ex: <input type="text" data-bind="value:Email" >

Using Knockoutjs in MVC:
   Create new MVC5 application using VS2013. First you have to add Knockoutjs library to your application by downloading library from or  use 'Manage nuget Packages' (search term 'knockoutjs'). After successful package install, you will find two scripts in Scripts folder like below.

  Then we have to add below Knockoutjs script in the 'View'.

<script src="~/Scripts/knockout-3.1.0.js" type="text/javascript"></script>


<script >
        $(document).ready(function () {

            function userViewmodel() {

                var self = this;
                // //bindings data to KO string Ex: self.Name=ko.observable("Prakash");  
                self.UserId = ko.observable("");
                self.FullName = ko.observable("");
                self.FirstName = ko.observable("");
                self.LastName = ko.observable("");
                self.Email = ko.observable("");
                self.Phone = ko.observable("");
                self.Address = ko.observable("");
                self.City = ko.observable("");
                self.State = ko.observable("");
                // Getting user info

                function getUserInfo() {

                    //Calling getJSON method
                    .done(function (data) {
                        //binding data 


            ko.applyBindings(new userViewmodel());



Now, write down your view.


        <div class="form-group">

            <label class="col-md-3 control-label">User Name</label>

            <div class="col-md-9">
                <label data-bind="text:FullName"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">First Name</label>

            <div class="col-md-9">
                <label data-bind="text:FirstName"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">Last Name</label>

            <div class="col-md-9">
                <label data-bind="text:LastName"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">Email</label>

            <div class="col-md-9"><label data-bind="text:Email"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">Phone</label>

            <div class="col-md-9"><label data-bind="text:Phone"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">Address</label>

            <div class="col-md-9"><label data-bind="text:Address"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">City</label>

            <div class="col-md-9"><label data-bind="text:City"></label>

        <div class="form-group">

            <label class="col-md-3 control-label">State</label>

           <div class="col-md-9"><label data-bind="text:State"></label>





Read More »