Using knockoutjs in MVC5

Rama Sagar
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 12122 red flag

Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates.For more info http://en.wikipedia.org/wiki/KnockoutJS

Introduction

This article explains how to display data using Knockout.js in MVC5..


Lets us start by creating a ASP.NET Web Application using MVC5 Template

Step 1: Open visual studio 2013 RC -> click on File -> New Project -> Create new ASP.NET WebApplication -> Select MVC--> Create

Step2: Lets Start working with Models Right click on Models Folder and add a class named Students and create properties as shown (prop tab tab)


Students.cs

namespace WebApplication5.Models
{
    public class Students
    {
        public int StudentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }

        
    }
}
Step 3: Create a Repository class as shown

StudentRepository

using System;
using System.Collections.Generic;

namespace WebApplication5.Models
{
    public class StudentRepository : IStudentRepository
    {
        private List<Students> studentList = new List<Students>();
        private int _nextId = 1;
         public StudentsRepository()
        {
            // Add Student records to display
            Add(new Students { StudentID = 1, FirstName = "Rama", LastName = "Sagar", City = "Alaska", Region = "WA", PostalCode = "98122", Country = "USA" });
            Add(new Students { StudentID = 2, FirstName = "chris", LastName = "Hammond", City = "Texas", Region = "WA", PostalCode = "98401", Country = "USA" });
            Add(new Students { StudentID = 3, FirstName = "srinivas", LastName = "saran", City = "Kirkland", Region = "WA", PostalCode = "98033", Country = "USA" });
            Add(new Students { StudentID = 4, FirstName = "Harish", LastName = "Shankar", City = "Redmond", Region = "WA", PostalCode = "98052", Country = "USA" });
            Add(new Students { StudentID = 5, FirstName = "Rakesh", LastName = "Raghav", City = "London", Region = "WA", PostalCode = "SW1 8JR", Country = "UK" });
            Add(new Students { StudentID = 6, FirstName = "suresh", LastName = "patiyala", City = "London", Region = "WA", PostalCode = "EC2 7JR", Country = "UK" });
            Add(new Students { StudentID = 7, FirstName = "babutunde", LastName = "avoke", City = "London", Region = "WA", PostalCode = "RG1 9SP", Country = "UK" });
            Add(new Students { StudentID = 8, FirstName = "smitha", LastName = "Basu", City = "Seattle", Region = "WA", PostalCode = "98105", Country = "USA" });
            Add(new Students { StudentID = 9, FirstName = "Rahul", LastName = "ragothi", City = "London", Region = "WA", PostalCode = "WG2 7LT", Country = "UK" });
        }


          public void Add(Students student)
        {
            throw new NotImplementedException();
        }
        public IEnumerable<Students> GetAll()
        {
            // Code to get the list of all the records in database
            return studentList;
        }
    }
}

IStudentRepository.cs


namespace WebApplication5.Models
{
    interface IStudentRepository
    {
        System.Collections.Generic.IEnumerable<Students> GetAll();
    }
}
Step 4: Lets work on controller class create a students controller and add the below code

using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    public class StudentsController : Controller
    {
        static readonly IStudentRepository repository = new StudentsRepository();
        //
        // GET: /Students/
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetAllStudents()
        {
            return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);

        }
    }
}
Step 5:Now Lets create a View 

<script src="~/Scripts/jquery-1.8.2.min.js"></script>

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

<script src='@Url.Content("~/Scripts/knockout-2.2.0.debug.js")'  type="text/javascript"></script>

<script type="text/javascript">

       function StudentsViewModel() {

        var self = this;

        //Declare observable

        self.StudentID = ko.observable("");

        self.FirstName = ko.observable("");

        self.LastName = ko.observable("");

        self.City = ko.observable("");

        self.Region = ko.observable("");

        self.PostalCode = ko.observable("");

        self.Country = ko.observable("");

        var Students= {

            StudentID: self.StudentID,

            FirstName: self.FirstName,

            LastName: self.LastName,

            City: self.City,

            Region: self.Region,

            PostalCode: self.PostalCode,

            Country: self.Country

        };

        self.student = ko.observable();

        self.Students = ko.observableArray();

        // Initialize the view-model

        $.ajax({

            url: '@Url.Action("GetAllStudents""Students")',

            cache: false,

            type: 'GET',

            contentType: 'application/json; charset=utf-8',

            data: {},

            success: function (data) {

                self.Students(data);

            }

        });

        $(document).ready(function () {

            var viewModel = new StudentsViewModel();

            ko.applyBindings(viewModel);

        });

    }

</script>

<h3>

   Students List</h3>

<table id="empl" data-bind="visible: Studnets().length > 0">

    <thead>

        <tr>

            <th>

                Student ID

            </th>

            <th>

                First Name

            </th>

            <th>

                Last Name

            </th>

            <th>

                City

            </th>

            <th>

                Region

            </th>

            <th>

                Postal Code

            </th>

            <th>

                Country

            </th>

        </tr>

    </thead>

    <tbody data-bind="foreach: Students">

        <tr>

            <td data-bind="text: StudnetID">

            </td>

            <td data-bind="text: FirstName">

            </td>

            <td data-bind="text: LastName">

            </td>

            <td data-bind="text: City">

            </td>

            <td data-bind="text: Region">

            </td>

            <td data-bind="text: PostalCode">

            </td>

            <td data-bind="text: Country">

            </td>

            <td>

           

                <button data-bind="click: $root.Remove">

                    Remove</button>

            </td>

        </tr>

    </tbody>

</table>



Conclusion

In this article we have learned how to work with Knockout.js and display data using Knockout.js

Reference

http://knockoutjs.com/
Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)