ASP.NET Web API教程(二) 獲取數據


  書接上文,打開上一個文章中的項目。(可以從上一個文章中下載到 ASP.NET Web API教程(一) 你的第一個Web API
添加類庫項目 Entities


添加用戶實體

public  class UserInfo
    {
         public  int Id {  getset; }
         public  string Name {  getset; }
         public  int Age {  getset; }
    }


添加數據以及數據操作

private List<UserInfo> Data =  new List<UserInfo>() { 
             new UserInfo(){
                Id= 1,
                Name= " 哈哈 ",
                Age= 10
            },
             new UserInfo(){
                Id= 2,
                Name= " 嘿嘿 ",
                Age= 19
            },
        };
         public IEnumerable<UserInfo> Get()
        {
             return Data;
        }

添加 UserInfoController


選擇 API Controller with empty read/write actions
添加Entities引用
修改Controller的 Get方法

BLL_UserInfo bll =  new BLL_UserInfo();
         //  GET api/userinfo
         public IEnumerable<UserInfo> Get()
        {
             return bll.Get();
        }


后台准備好了,開始編寫前台了
添加新頁面以及內容
第一步引入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>

 

第二步編寫顯示模板

< href ="javascript:void()"  id ="getUserInfos" >獲取 </ 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 >

 

第三步 編寫JS

< script  type ="text/javascript" >
            viewModel 
=  {
                userinfos: ko.observableArray([])
            };

            ko.applyBindings(viewModel);

            $(
function  () {
                $(
" #getUserInfos " ).click( function  () {
                    
//  使用 Knockout 模型. 首先清空一下UserInfos.
                    viewModel.userinfos([]);

                    $.get(
' /api/userInfo ' function  (data) {
                        
//  從API中
                         //  得到返回的數據,更新 Knockout 模型並且綁定到頁面UI模板中                         
                        viewModel.userinfos(data);
                    });

                });
            });
        
</ script >


 

運行點擊得到結果:


本章內容源碼下載:/Files/risk/web api 2/MvcApplication1.rar


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM