Link the book to open the previousArticleProject. (You can download the ASP. NET web API tutorial from the previous article (1) Your first web API)
Add a class library project entities
Add User entity
Public Class Userinfo
{
Public Int Id { Get ; Set ;}
Public String Name { Get ; Set ;}
Public Int Age { Get ; Set ;}
}
Add data and data operations
Private List <userinfo> DATA = New List <userinfo> (){
New Userinfo (){
Id = 1 ,
Name = " Haha " ,
Age = 10
},
New Userinfo (){
Id = 2 ,
Name = " Hey " ,
Age = 19
},
};
Public Ienumerable <userinfo> get ()
{
Return Data;
}
Add userinfocontroller
SelectAPI controller with empty read/write actions
Add entities reference
Modify the get method of Controller
Bll_userinfo BLL = New Bll_userinfo ();
// Get API/userinfo
Public Ienumerable <userinfo> get ()
{
Return Bll. Get ();
}
The background is ready, and the foreground is ready.
Add new pages and content
Step 1 introduce JS
<SCRIPT src = " Scripts/jquery-1.7.1.min.js " Type = " Text/JavaScript " > </SCRIPT>
<SCRIPT src = " Scripts/knockout-2.1.0.js " Type = " Text/JavaScript " > </SCRIPT>
Step 2 compile a display template
< A Href = "Javascript: void ()" ID = "Getuserinfos" > Obtain </ A >
< Ul Data-bind = "Template: {Name: 'userinfotemplate', foreach: userinfos }" >
</ Ul >
< Script ID = "Userinfotemplate" Type = "Text/html" >
< Li class = " Userinfo " >
< Header >
< Div class = " Info " >
< Strong > < Span data - Bind = " Text: Name " > < / Span> < / Strong >
< / Div>
< / Header>
< Div class = " Body " >
< P Data - Bind = " Text: Age " > < / P>
< / Div>
< / LI>
</ Script >
Step 3 Write JS
< Script Type = "Text/JavaScript" >
Viewmodel = {
Userinfos: KO. observablearray ([])
};
Ko. applybindings (viewmodel );
$ ( Function (){
$ ( " # Getuserinfos " ). Click ( Function (){
// Use the knockout model. First clear userinfos.
Viewmodel. userinfos ([]);
$. Get ( ' /API/userinfo ' , Function (Data ){
// From API
// Obtain the returned data, update the knockout model, and bind it to the page UI template.
Viewmodel. userinfos (data );
});
});
});
</Script>
Click Run to get the result:
Download the source code of this chapter:/files/risk/web API 2/mvcapplication1.rar