uid | title | author | description | ms.author | ms.date | ms.assetid | msc.legacyurl | msc.type |
---|---|---|---|---|---|---|---|---|
web-api/overview/data/using-web-api-with-entity-framework/part-7 |
Create the View (UI) | Microsoft Docs |
Rick-Anderson |
Describes how to define the application's HTML and add data binding between the HTML and the view model. |
riande |
06/16/2014 |
b2445062-a1fe-4133-8994-f510280f6d9a |
/web-api/overview/data/using-web-api-with-entity-framework/part-7 |
authoredcontent |
In this section, you will start to define the HTML for the app, and add data binding between the HTML and the view model.
Open the file Views/Home/Index.cshtml. Replace the entire contents of that file with the following.
[!code-cshtmlMain]
Most of the div
elements are there for Bootstrap styling. The important elements are the ones with data-bind
attributes. This attribute links the HTML to the view model.
For example:
[!code-htmlMain]
In this example, the "text
" binding causes the <p>
element to show the value of the error
property from the view model. Recall that error
was declared as a ko.observable
:
[!code-javascriptMain]
Whenever a new value is assigned to error
, Knockout updates the text in the <p>
element.
The foreach
binding tells Knockout to loop through the contents of the books
array. For each item in the array, Knockout creates a new <li> element. Bindings inside the context of the foreach
refer to properties on the array item. For example:
[!code-htmlMain]
Here the text
binding reads the Author property of each book.
If you run the application now, it should look like this:
The list of books loads asynchronously, after the page loads. Right now, the "Details" links are not functional. We'll add this functionality in the next section.