Click here to Skip to main content
Licence CPOL
First Posted 19 Feb 2012
Views 5,620
Bookmarked 2 times

Client side Model binding with ASP.NET MVC 3 and KnockoutJs

By | 19 Feb 2012 | Technical Blog
Client side Model binding with ASP.NET MVC 3 and KnockoutJs
A Technical Blog article. View original blog here.[^]

Client side Model binding with ASP.NET MVC 3 and KnockoutJs Knockoutjs is a type safe client side library which provides declarative bindings of DOM with model data, Automatic UI refresh when view model changes, etc. You can read more about KnockoutJS on its website. You can read more about AspNet MVC3 on ASP.NET MVC website.

Model

Create Model class on server side MarketPriceModel, its collection class MarketPriceCollectionModel.

public class MarketPriceCollectionModel
    {
        public List Prices { get; private set; }

        public void Add(MarketPriceModel model)
        {
            if (Prices == null)
                Prices = new List();
            Prices.Add(model);
        }
    }

    public class MarketPriceModel
    {
        public string Symbol { get; set; }
        public double Open { get; set; }
        public double Close { get; set; }
        public double Low { get; set; }
        public double High { get; set; }
        public DateTime TimeStamp { get; set; }
    }

Controller: MarketWatchController

This controller class has action method “MarketPriceUI” which returns MarketPriceUI view and injects MarketPriceCollectionModel class as model.

public class MarketWatchController : Controller
    {
        //
        // GET: /MarketWatch/

        public ActionResult MarketPriceUI()
        {
         MarketPriceCollectionModel collection = new MarketPriceCollectionModel();
         collection.Add(new MarketPriceModel() { Symbol = "MSFT",
        Open = 34.5d, Close = 35.5d, Low = 33.4d, High = 36.5d });
         collection.Add(new MarketPriceModel() { Symbol = "Goog",
        Open = 54.5d, Close = 58.65d, Low = 52.78d, High = 59.23d });

         return View(collection);
        }
    }

View MarketPriceUI.cshtml @model: contains object returns from controller. We can use this object to show data in view, but here I want to convert @model to knockoutJS viewmodel.

var initialData = @(Html.Raw(Json.Encode(Model.Prices)));

viewModel = {prices: ko.observableArray(initialData)
                };

           ko.applyBindings(viewModel);
  • @(Html.Raw(Json.Encode(Model.Prices))) converts model data into json and this data is set as observablearray for knockoutjs viewmodel.
  • “data-bind="foreach: viewModel.prices" statement can loop in this viewmodel to show data on page.
@model MarketWatchWebSample.Models.MarketPriceCollectionModel
@{
    ViewBag.Title = "MarketWatch";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

var viewModel;
    $(document).ready(function () {

            var initialData = @(Html.Raw(Json.Encode(Model.Prices)));

viewModel = {prices: ko.observableArray(initialData)
                };

           ko.applyBindings(viewModel);
});

}

<table>
      <tr> 
        <td> 
            Symbol 
        </td> 
        <td> 
            High 
        </td> 
        <td> 
            Low 
        </td> 
    </tr> 
    <tbody data-bind="foreach: viewModel.prices"> 
        <tr> 
            <td> 
                <span data-bind="text:Symbol"></span> 
            </td> 
            <td> 
                <span data-bind="text:High"></span> 
            </td> 
            <td> 
                <span data-bind="text:Low"></span> 
            </td> 
        </tr> 
    </tbody> 
</table>

Output

image


License

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

About the Author

Neeraj Kaushik 1980

Architect
Initto Technologies India Pvt Ltd
India India

Member

Follow on Twitter Follow on Twitter
• Technical Architect with 9 years of Application development experience
• Good knowledge and expertise on multiple areas of technologies and their business applications
• Strong experience in high performance and business critical applications.
• Experience in creating framework, Code generators, and UML diagrams.
• Developed messaging framework for Algo Trading, technical analysis tool, market feed client Api, Payment Solutions for SWIFT, Internationalization for Core Banking Solution product etc.
• Practical knowledge of building and practicing agile delivery methodologies (SCRUM & TDD).
• Proven ability in producing technical documentation and presentation to clients.
• Active participation in trainings, article writing & taking initiatives.
• Passion to get knowledge from various resources acquires best practices.
• Good understanding of financial domain especially in investment banking and banking domain.
Specialties
 
Technical Architectures, Multi-threading Architecture, Algo Trading systems, Messaging Framework, FIX Implementation, Technical Analysis & Charting, ActiveMQ, MSMQ, C#, WinForms, ASP.NET MVC, Jquery, WCF, Sql Server 2008, Oracle, TFS, TDD, QuickFix, Open Source Tools & Framework.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralJust what I was looking for... PinmemberJeremy Albright2:46 13 Mar '12  
QuestionScript tags missing in fourth code block PinmemberNic_Roche12:28 19 Feb '12  
AnswerRe: Script tags missing in fourth code block PinmemberNeeraj Kaushik 198019:52 19 Feb '12  
GeneralMy vote of 2 PinmemberDean Oliver6:03 19 Feb '12  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 20 Feb 2012
Article Copyright 2012 by Neeraj Kaushik 1980
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid