Knockout website example implementation under MVC-01, Implementing Hello World

Source: Internet
Author: User

This article uses knockout to implement "Hello World" under MVC, the corresponding official website instance is here.

View views

One feature of knockout is the declarative binding, the declarative bindings. Regardless of the business logic, focus on the interface UI, the second "V" in "MVVM" mode, which is the view view. Based on the syntax of Knockout, create the following interface:

<div>        <p>first name:<input data-bind="value:firstname" /></p >        <p>last name:<input data-bind="value:lastname" /></p>        "text:fullname"></span>!

Model Domain Models

For MVC, there should be a domain model corresponding to the first "M" in the "MVVM" pattern:

namespacemymvcknockout.models{ Public classHelloworldmodel { Public stringFirstName {Get;Set; }  Public stringLastName {Get;Set; }  Public stringFullName {Get{returnFirstName +" "+LastName;} }     }}

Next, let the Gethelloworld method of the HelloWorld controller provide the return data in JSON format:

usingSYSTEM.WEB.MVC;usingMymvcknockout.models;namespacemymvcknockout.controllers{ Public classHelloworldcontroller:controller { PublicActionResult Index () {returnView (); }         PublicJsonresult Gethelloworld () {varModel =NewHelloworldmodel () {FirstName ="Darren", LastName ="ji" }; returnJson (model, jsonrequestbehavior.allowget); }    }}

View model views

Now that the domain model is available, the view UI is there, and next, you need to bind the view model to the views UI. The purpose of the binding is to: When the view UI changes, the view model also changes and vice versa. This is knockout's declared "elegant dependency tracking", an elegant reliance on tracking. How do we do that?

Roughly two steps. First, Knockout uses the Ko.observable (), Ko.observablearray () method to make the properties and collection properties of the view model "observable". Then, use Ko.applybindings () to bind the view model with the views UI. Finally did "elegant dependency tracking".

The first step: Create the View Model and make the relevant properties "Observable" features.

function ViewModel () {            varthis;             = Ko.observable ("");             = Ko.observable ("");             = ko.computed (function () {                return"" + self.lastname ();            });          }

Above, FirstName and LastName have the characteristics of "Observable", fullname value is calculated by Ko.computed () method.

Step Two: Use Ko.applybindings () to bind the view model and the view UI.

$ (function () {            varnew  ViewModel ();            Ko.applybindings (Myviewmodel);            $.getjson ('@Url. Action ("Gethelloworld", "HelloWorld")', function (data) {                myviewmodel.firstname (data. FirstName);                Myviewmodel.lastname (data. LastName);         });

Above, through Ko.applybindings (Myviewmodel), the view model and the UI bindings are implemented. If you want to bind different view model to different views UI, you should use the Ko.applybindings (Myviewmodel, document.getElementById (' Someelementid ')) method.

ViewModel, the initial value of Fristname,lastname is empty, and the above is re-assigned to Fristname,lastname by the callback function of $.getjson (). From the final display of the interface effect, through the knockout binding mechanism, with the change of the view model, its corresponding UI content has indeed changed.

The helloworld/index.cshtml view is complete as follows:

@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title> <script src="~/scripts/jquery-1.8.2.js"></script> <script src="~/scripts/knockout-3.1.0.js"></script> <script type="Text/javascript">$ (function () {varMyviewmodel =NewViewModel ();            Ko.applybindings (Myviewmodel); $.getjson ('@Url. Action ("Gethelloworld", "HelloWorld")', function (data) {myviewmodel.firstname (data).                FirstName); Myviewmodel.lastname (data.            LastName);        });        }); function ViewModel () {varSelf = This; Self.firstname= Ko.observable (""); Self.lastname= Ko.observable (""); Self.fullname=ko.computed (function () {returnSelf.firstname () +" "+Self.lastname ();          }); }    </script>"Value:firstname"/></p> <p>last name:<input data-bind="Value:lastname"/></p> "Text:fullname"></span>!

"The implementation of the knockout website example under MVC" series includes:

Knockout the implementation of the official website example under MVC-01, implementation of the Hello Worldknockout official website instance under the MVC implementation-02, the realization counts the time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.