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

转载于:https://www.cnblogs.com/risk/archive/2012/08/22/2650771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值