Build a simple crud application with the Knockout.js + ASP. NET Web API

Source: Internet
Author: User

REFERENCE from:http://www.cnblogs.com/artech/archive/2012/07/04/knockout-web-api.html

Enterprise Web Apps require less user experience than Web sites for end consumers. However, the customer requirements for "user experience" is "increasing", many users who are "spoiled" can not tolerate the postback brought by the page refresh, so Ajax has been widely used in enterprise-level Web applications. One of the features of enterprise Web applications is "data processing", so the "bind-oriented" knockout.js is a good choice. ASP. NET Web API, as. NET platform is the best Rest service development platform (primarily compared to WCF), you can provide background processing of data in the form of a service.

One simple crud-based Web applications

In creating a simple Web App through ASP. NET Web API + jquery, I used the jquery + ASP. NET Web API to build a simple crud operation on a single data, and for the rendering of data on the interface, I was using jquery The way HTML is generated dynamically. Now that we have data binding through knockout.js, you will find that our code becomes very elegant.

This simple demo app simulates "contact management". When the page loads, all the contact lists are listed. On the same page, we can add a new contact, and you can modify and delete existing contact information. The entire app's unique page renders as shown in the browser.

Ii. providing services through the ASP. NET Web API

Let's take a look at the definition of Apicontroller. As shown in the following code snippet, we defined a apicontroller called Contactscontroller to complete the crud operation against the contact, using the HTTP Method (Get, Post, Put and delete) name the action method because the HTTP method is used as a prefix to match when an action match is made.

   1:public class Contactscontroller:apicontroller
   2: {
   3:     private static list<contact> contacts = new list<contact>
   4:     {
   5:         new contact{Id = "001", FirstName = "San", lastname= "Zhang", phoneno= "123", emailaddress= "[email protected]"},
   6:         new contact{Id = "002", FirstName = "Si", lastname= "Li", phoneno= "456", emailaddress= "[email protected]"}
   7:     };
   
   9: Public     ienumerable<contact> Get ()
  Ten:     {
  One:         return contacts;
  :     }
  
  +: Public Contact     Get (string id)
  :     {
  :         return contacts. FirstOrDefault (c = c.id = = Id);
  :     }
  
  : Public     void Put
  :     {
  +: Contact         . Id = Guid.NewGuid (). ToString ();
  A:         contacts. ADD (contact);
  :     }
  
  : Public     void Post
  :     {
  :         Delete (Contact. ID);
  :         contacts. ADD (contact);
  :     }
  
  : Public     void Delete (string id)
  :     {
  : Contact Contact         = Contacts. FirstOrDefault (c = c.id = = Id);
  :         contacts. Remove (contact);
  :     }
  36:}
  
  38:public class Contact
  39: {
  Max: Public     string Id {get; set;}
  In: Public     string FirstName {get; set;}
  All: Public     string LastName {get; set;}
  : Public     string Phoneno {get; set;}
  : Public     string EmailAddress {get; set;}
  45:}

Like the ASP. NET MVC Web application, we also use URL routing mechanism to map the request address to the target Controller and action. The path to the API default registration is as follows (the method called here is Maphttproute instead of Maproute).

   1:public class Routeconfig
   2: {
   3: Public     static void RegisterRoutes (RouteCollection routes)
   4:     {
   5:         routes. Maphttproute (
   6:             Name: "Defaultapi",
   7:             routetemplate: "Api/{controller}/{id}",
   8:             defaults:new {id = routeparameter.optional}
   9:         );
  Ten:     }
  11:}

According to the registered routing rules and the default innuendo mechanism of the action method name and HTTP method, we can access the address "/api/contacts" and "/api/contacts/001" directly in the browser to get all the contact list and id "001" Contact information. The results are as shown.

third, Ajax calls through jquery, using knockout.js for data binding

We build a web App with ASP. HomeController, the default is defined as follows, and the default index operation simply renders the default view.

   1:public class Homecontroller:controller
   2: {
   3: Public     actionresult Index ()
   4:     {
   5:         return View ();
   6:     }
   7:}

Here is the definition of the entire view. We use jquery for Ajax calls Apicontroller to get, add, modify, and delete contacts, and the binding of data and commands (additions, modifications, and deletions) is done through Knockout.js.

   1: <! DOCTYPE html>
   2: 
   3:     
   4:         <title> @ViewBag. Title-my asp application</title>
   5:         @Styles. Render ("~/content/css")
   6:         <script type= "Text/javascript" src= ". /.. /scripts/jquery-1.6.2.min.js "></script>
   
   2:         <script type= "Text/javascript" src= ". /.. /scripts/knockout-2.0.0.js ">
   1: </script>       
   2:     
   3:     <body>
   4:     <div id= "Contacts" >
   5:          <table>
   6:             <tr>
   7:                 <th>first name</th>
   8:                 <th>last name</th>
   9:                 <th>phone no.</th>
  Ten:                 <th>email address</th>
  One:                 <th></th>
  :             </tr>
  :             <tbody>
  :                 <!--ko Foreach:contacts--
  :                 <tr>
  :                     <td data-bind= "Text:firstname"/>
  Page:                     <td data-bind= "Text:lastname"/>
  :                     <td data-bind= "Text:phoneno"/>
  :                     <td><input type= "text" class= "textbox Long" data-bind= "value:emailaddress"/></td>
  :                     <td>
  £                         <a href= "#" data-bind= "click: $root. Updatecontact" >update</a><a href= "#" data-bind= "click: $ Root.deletecontact ">Delete</a>
  :                     </td>
  :                 </tr>
  :                 <!--/ko--
  :                 <tr data-bind= "With:addedcontact" >
  :                     <td><input type= "text" class= "textbox" data-bind= "Value:firstname" </td>
  :                     <td><input type= "text" class= "textbox" data-bind= "Value:lastname" </td>
  :                     <td><input type= "text" class= "textbox" data-bind= "Value:phoneno" </td>
  In:                     <td><input type= "text" class= "textbox Long" data-bind= "value:emailaddress" </td>
  :                     <td><a href= "#" data-bind= "click: $root. Addcontact" >Add</a></td>
  :                 </tr>
  :             </tbody>
  :         </table>
  :     </div>
  :     <script type= "Text/javascript" >
  :         function Contactmanagermodel () {
  PNS: Self             = this;
  £             self.contacts = Ko.observablearray ();
  A:             self.addedcontact = ko.observable ();
  
  In:             self.loadcontacts = function () {
  :                 $.get ("/api/contacts", NULL, function (data) {
  :                     self.contacts (data);
  :                     var emptycontact = {Id: "-1", FirstName: "", LastName: ", Phoneno:" ", EmailAddress:" "};
  :                     self.addedcontact (emptycontact);
  :                     $ ("Table Tr:odd"). AddClass ("Oddrow");
  :                 });
  :             };
  
  :             self.addcontact = function (data) {
  !self.validate:                 if (data) {
  :                     return;
  :                 }
  Wu:                 $.ajax ({
  :                     URL: "api/contacts/",
  £ º                     data:self.addedContact (),
  Page:                     type: "PUT",
  :                     success:self.loadContacts
  :                 });
  :             };
  
  +:             self.updatecontact = function (data) {
  :                 $.ajax ({
  Page:                     URL: "api/contacts/" + data. Id
  A:                     data:data,
  :                     type: "POST",
  Success:self.loadContacts:                     
  :                 });                        
  :             };
  
  :             self.deletecontact = function (data) {
  A:                 $.ajax ({
  :                     URL: "api/contacts/" + data. Id
  A:                     type: "DELETE",
  Success:self.loadContacts:                     
  :                 });
  :             };
  
  :             self.validate = function (data) {
  A:                 if (data. FirstName && data. LastName && data. Phoneno && data. EmailAddress) {
  Bayi:                     return true;
  :                 }
  Provide:                 alert ("Please information!");
  +:                 return false;
  :             }
  :             self.loadcontacts ();
  :         }
  :         ko.applybindings (New Contactmanagermodel ());
  89:     
</script>
   7:     </body>
   8: 

Build a simple crud application with the Knockout.js + ASP. NET Web API

Related Article

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.