Knockout MVC4 KnockoutJs using JSON and Ajax

Knockout MVC4 KnockoutJs using JSON and Ajax

Hi Everyone,

I'm going to share code sample for display student matters using Knockoutjs, mvc 4, json and ajax.

Simple Application using Knockout jQuery, Ajax, Json and MVC 4

Table of Contents

1. In the 1st step, code-sample for view-Model.
2. In the 2nd step, code-sample for View.
3. In the 3rd step, code-sample for Model.

In the 1st step, code sample for view Model

<script type="text/javascript">
    // Initialized the matters namespace.
    var studentMatters= {};

    // View model declaration.
    studentMatters.initViewModel = function (matters) {
        var matterViewModel = {
            studMatterId: ko.observable(matters.studMatterId),
            studMatterTitle: ko.observable(matters.studMatterTitle),
            studMatterComment: ko.observable(matters.studMatterComment),
            createdOn: ko.observable(matters.createdOn)
        return matterViewModel;

    // Bind to the matters.
    studentMatters.bindData = function (matters) {
        // Create the view model
        var viewModel = studentMatters.initViewModel(matters);
        //applying knockout bindings.

    studentMatters.getmatter = function (studMatterId) {
            url: "/StudentController/Matters/",
            type: 'post',
            data: "{'studMatterId':'stud01' }",
            contentType: 'application/json',
            success: function (result) {
            error: function (jqXHR, textStatus, errorThrown) {

    $(document).ready(function () {


In the 2nd step, code sample for view

 <div data-role="listview">
      <span data-bind="text: studMatterId"></span>
      <p data-bind="text: studMatterTitle" />                         
      <p data-bind="text: createdOn" />
      <p data-bind="text: studMatterComment" />


In the 3rd step, code sample for Model

public class StudentController : Controller
    public ActionResult Index()
        return View();

    public JsonResult Matters(int MatterId)
        stdMatter matter = new stdMatter
            studMatterId = MatterId,
            studMatterTitle = "about knockoutjs.",
            createdOn = DateTime.Now,
            studMatterComment = "Something details for knockoutjs."
        return Json(matter);

    public class stdMatter
        public int studMatterId { get; set; }
        public string studMatterTitle { get; set; }
        public DateTime createdOn { get; set; }
        public string studMatterComment { get; set; }


Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions