Click here to Skip to main content
15,881,882 members
Articles / Web Development / HTML
Tip/Trick

Simplest knockoutJS and MVC4 Demo

Rate me:
Please Sign up or sign in to vote.
4.64/5 (12 votes)
26 Dec 2013CPOL1 min read 41.3K   757   15   4
MVC 4 knockoutJS project at bare minimum

Introduction

This is a C# MVC web project with Knockout JS at its bare minimum. It only contains MVC 4, KnockoutJS 3.0, and jQuery 2.0.3. Irrelevant packages are not added.

Background

I have been searching for the most simplistic example of MVC knockout web project. But unfortunately, I could not find any. Most of the examples are loaded with irrelevant extras. So I ended up spending a day writing and wiring up this simple demo. Feel free to download it.

The ingredients of this project are:

  1. Microsoft MVC 4.0
  2. KnockoutJS 3.0 - its backward compatible with 2.2.0
  3. jQuery 2.0.3. - should be compatible with jQuery 1.7

This project strives to be the most simplistic example of MVC-KnockoutJS wire up with the least number of files, so I am intentionally not having the following:

  • No Entity Framework (yes, you can have MVC without EF)
  • No KnockoutJS Mapping package
  • No irrelevant jQuery packages (jQueryUI, jQuery validation)
  • No CSS
  • No bundling nor modularizing
  • No Modernizr
  • No support for old browsers. I use Chrome for developing this.
  • No Injection container

Using the Code

This project uses MVC4 "Empty" project template and is written from the ground up. Only 3 files are manually written:

Model\Person.cs

C#
namespace KnockoutJsonDemo.Models
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Controller\HomeController.cs

C#
using System.Web.Mvc;
using KnockoutJsonDemo.Models;
using Newtonsoft.Json;

namespace KnockoutJsonDemo.Controllers
{
    public class HomeController : Controller
    {
        private static Person _data = new Person()
        {
            Name = "PersonName",
            Age = 25
        };

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult TestJson()
        {
            return Json(new
                {
                    Name = "MyName",
                    Age = "17"
                }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetPerson()
        {
            return Json(_data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult UpdatePerson()
        {
            string jsonString = Request.Form[0];
            Person person = JsonConvert.DeserializeObject<Person>(jsonString);
            _data.Name = person.Name;
            _data.Age = person.Age;
            return Json(_data);
        }
    }
}

View\Home\Index.cshtml

This is equipped with knockoutJS.

JavaScript
@{
    ViewBag.Title = "KnockoutJs client";
}

<h2>KnockoutJs client</h2>

<div>
    <p>Name: <input data-bind='value: displayName' /></p> 
    <p>Age: <input data-bind='value: displayAge' /></p> 
    <p>Name Age: <input data-bind='value: displayNameAge' /></p> 
    <button data-bind='click: loadFromServer'>Load From Server</button>
</div>

<div>
    <h2>Input</h2>
        <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>
</div>

<div>
    <h2>KO Content</h2>
    <pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
</div>

<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/knockout-3.0.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("My Name");
        self.inputAge = ko.observable("15");
        self.updateLocal = function() {
            self.displayName(self.inputName());
            self.displayAge(self.inputAge());
        };

        self.loadFromServer = function () {
            $.getJSON("/home/GetPerson", function (data) {
                self.updateThis(data);
            });
        };

        self.updateServer = function() {
            var data = "{ \"name\" : \"" + self.inputName() + 
              "\", \"age\" : \"" + self.inputAge() + "\"}";
            console.log(data);
            $.post("/home/UpdatePerson", 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("Jay Tan", "21");
    ko.applyBindings(myViewModel); // This makes Knockout get to work
</script>

I hope this small demo will help you. If you can make this example simpler, please let me know. Feedback is appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Jeson Martajaya is a Senior Consultant for Magenic, a leading consulting firm in the US specializes in .NET and Mobile development. He has been professionally coding for more than 13 years, ranging from Java to Oracle to Windows and ASP.NET. He is enjoying it very much. He holds multiple professional credentials: Oracle Certified Associate (OCA) in PL/SQL, Microsoft Certified Professional Developer (MCPD) in Windows Application, and two Microsoft Certified Solutions Developer (MCSD) in Web Development as well as in Application Lifecycle Management.

Comments and Discussions

 
QuestionIt compiles :) Pin
Gluups11-Dec-15 2:35
Gluups11-Dec-15 2:35 
QuestionDownload Pin
paulg791127-Jan-15 3:13
paulg791127-Jan-15 3:13 
AnswerRe: Download Pin
Jeson Martajaya30-Jan-15 7:35
Jeson Martajaya30-Jan-15 7:35 
AnswerRe: Download Pin
Jeson Martajaya4-Feb-15 10:20
Jeson Martajaya4-Feb-15 10:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.