Click here to Skip to main content
13,055,884 members (49,751 online)
Click here to Skip to main content
Add your own
alternative version

Stats

30K views
7 bookmarked
Posted 19 Feb 2012

Client Side Model Binding with ASP.NET MVC 3 and KnockoutJs

, 19 Feb 2012
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Neeraj Kaushik1980
Architect Saxo Bank A/S
Denmark Denmark
• Solution Architect /Principle Lead Developer with 12 years of IT experience with more emphasize on Capital Domain and Investment banking domain.
• Strong experience in Continuous Integration, Delivery and DevOps solutions.
• Strong experience in drafting solutions, stakeholder communications and risk management.
• Proved strong coding and designing skills with agile approaches (TDD, XP framework, Pair Programming).
• Delivered many projects with involvement from inception to delivery phase.
• Strong experience in high performance, multithreaded, low latency applications.
• Ability to communicate with the business and technical stake holders effectively.
• Have extensive experience in Capital Market Domain: Front Office & BackOffice (Algorithm Trading tools, messaging framework, Enterprise bus, integration of FIX APIs and many trading APIs).
• Functional knowledge of Portfolio/Wealth Management, Equities, Fixed Income, Derivatives, Forex.
• Practical knowledge of building and practicing agile delivery methodologies (SCRUM, TDD, Kanban).

Technical Skills

• Architectural: Solution Design, Architectural Presentations (Logical, Component, Physical, UML diagrams)
• Languages: C#, C++
• Server Technologies: WCF, Web API,
• Middle Ware: ActiveMQ, RabbitMQ, Enterprise Service Bus
• UI Technologies: Winforms and WPF
• Web Technologies: Asp.Net Mvc, KnockOutJS, JQuery, Advance Java Scripts Concepts
• Databases: Sql Server 2008 +, MySQL
• Tools/Frameworks: TFS, SVN, NUnit, Rhino Mocks, Unity, NAnt, QuickFix/n, Nhibernate, LINQ, JIRA,

Functional Skills

• Wealth Management System, Trade Life Cycle, Trading Components and their integrations
• Working knowledge of Stocks, Bonds, CFDs,Forex, Futures and Options
• Pricing Systems, Market Data Management,
• BackOffice Processes : Settlement Processes, Netting, Tax, Commissions, Corporate Actions Handling,
• Reporting Solutions : OLTP and OLAP Data model designing
• FIX Engine implementation and integration

You may also be interested in...

Comments and Discussions

 
QuestionIs KO is better then Telrik with MV3? Pin
am.net15-Jan-13 20:46
memberam.net15-Jan-13 20:46 
AnswerRe: Is KO is better then Telrik with MV3? Pin
Neeraj Kaushik 198016-Jan-13 1:04
memberNeeraj Kaushik 198016-Jan-13 1:04 
GeneralRe: Is KO is better then Telrik with MV3? Pin
am.net16-Jan-13 5:53
memberam.net16-Jan-13 5:53 
GeneralMy vote of 5 Pin
Denis Vuyka9-Oct-12 9:06
memberDenis Vuyka9-Oct-12 9:06 
QuestionHow to create, edit, update and delete record Pin
Riuraj24-Jul-12 10:07
memberRiuraj24-Jul-12 10:07 
AnswerRe: How to create, edit, update and delete record Pin
Neeraj Kaushik 19801-Aug-12 7:53
memberNeeraj Kaushik 19801-Aug-12 7:53 
Question[My vote of 2] Source Download? Pin
JoeCane17-Jul-12 13:44
memberJoeCane17-Jul-12 13:44 
GeneralJust what I was looking for... Pin
Jeremy Albright13-Mar-12 2:46
memberJeremy Albright13-Mar-12 2:46 
QuestionScript tags missing in fourth code block Pin
Nic_Roche19-Feb-12 12:28
memberNic_Roche19-Feb-12 12:28 
AnswerRe: Script tags missing in fourth code block Pin
Neeraj Kaushik 198019-Feb-12 19:52
memberNeeraj Kaushik 198019-Feb-12 19:52 
GeneralMy vote of 2 Pin
Dean Oliver19-Feb-12 6:03
memberDean Oliver19-Feb-12 6:03 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 20 Feb 2012
Article Copyright 2012 by Neeraj Kaushik1980
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid