"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Create the View (UI)

by Mike Wasson

Download Completed Project

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]

   1:  @section scripts {
   2:    @Scripts.Render("~/bundles/app")
   3:  }
   4:   
   5:  <div class="page-header">
   6:    <h1>BookService</h1>
   7:  </div>
   8:   
   9:  <div class="row">
  10:   
  11:    <div class="col-md-4">
  12:      <div class="panel panel-default">
  13:        <div class="panel-heading">
  14:          <h2 class="panel-title">Books</h2>
  15:        </div>
  16:        <div class="panel-body">
  17:          <ul class="list-unstyled" data-bind="foreach: books">
  18:            <li>
  19:              <strong><span data-bind="text: AuthorName"></span></strong>: <span data-bind="text: Title"></span>
  20:              <small><a href="#">Details</a></small>
  21:            </li>
  22:          </ul>
  23:        </div>
  24:      </div>
  25:      <div class="alert alert-danger" data-bind="visible: error"><p data-bind="text: error"></p></div>
  26:    </div>
  27:   
  28:    <div class="col-md-4">
  29:      <!-- TODO: Book details -->
  30:    </div>
  31:   
  32:    <div class="col-md-4">
  33:      <!-- TODO: Add new book -->
  34:    </div>
  35:  </div>

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]

   1:  <p data-bind="text: error">

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]

   1:  self.error = ko.observable();

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]

   1:  <span data-bind="text: Author"></span>

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.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-7.htm
< THANKS ME>