Hello world


This sample is a simple demonstration of basic features of Knockout MVC. Our model contains two common text properties: FirstName and LastName. Besides, there is Expression<Func<string>> function that will be converted to JavaScript function (you can see it in the generated html). Thus, a simple JavaScript application will be generated based on our C# code; the application can work without server connection. We set what interface elements correspond to model properties in the Razor template (including calculated property FullName). It is possible to set initial values for model properties in the controller.

Please pay attention to the fact that lable corresponding to FullName is updated automatically — you don’t need to write any additional code to catch onchange event in JavaScript code.

The original example: http://knockoutjs.com/examples/helloWorld.html

Live example

First name:

Last name:

Hello, !


public class HelloWorldModel
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName
        get { return FirstName + " " + LastName; }


@using PerpetuumSoft.Knockout
@model KnockoutMvcDemo.Models.HelloWorldModel           
  var ko = Html.CreateKnockoutContext();
<p>First name: @ko.Html.TextBox(m => m.FirstName)</p>
<p>Last name: @ko.Html.TextBox(m => m.LastName)</p>
<h2>Hello, @ko.Html.Span(m => m.FullName)!</h2>



public class HelloWorldController : BaseController
    public ActionResult Index()
        InitializeViewBag("Hello world");
        return View(new HelloWorldModel
            FirstName = "Steve",
            LastName = "Sanderson"

Html (autogenerated)

<p>First name: <input data-bind="value : FirstName" name="FirstName" type="text" /></p>
<p>Last name: <input data-bind="value : LastName" name="LastName" type="text" /></p>
<h2>Hello, <span data-bind="text : FullName"></span>!</h2>

<script type="text/javascript"> 
var viewModelJs = {"FirstName":"Steve","LastName":"Sanderson"};
var viewModel = ko.mapping.fromJS(viewModelJs); 
viewModel.FullName = ko.computed(function() { try { return ((this.FirstName() + ' ') + this.LastName())} catch(e) { return null; }  ;}, viewModel);