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:
- Microsoft MVC 4.0
- KnockoutJS 3.0 - its backward compatible with 2.2.0
-
jQuery 2.0.3. - should be compatible with jQuery 1.7
This project strive to be the most simplistic example of MVC-KnockoutJS
wire up with the least number of files, so I 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 using MVC4 "Empty" project template and written from the ground up. Only 3 files are manually written:
Model\Person.cs
namespace KnockoutJsonDemo.Models
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
Controller\HomeController.cs
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.
@{
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); </script>
I hope this small demo will help you. If you can make this example simpler, please let me know. Feedback is appreciated.