书接上文,打开上一个文章中的项目。(可以从上一个文章中下载到 ASP.NET Web API教程(一) 你的第一个Web API
添加类库项目 Entities

ASP.NET Web API教程(二) 获取数据


添加用户实体

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

ASP.NET Web API教程(二) 获取数据


选择 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>


 

运行点击得到结果:

ASP.NET Web API教程(二) 获取数据


本章内容源码下载:/Files/risk/web api 2/MvcApplication1.rar

相关文章:

  • 2021-12-31
  • 2022-02-07
  • 2022-01-27
  • 2021-07-05
  • 2022-01-14
  • 2021-07-13
  • 2021-06-27
猜你喜欢
  • 2021-09-09
  • 2021-06-21
  • 2021-08-01
  • 2021-08-01
  • 2022-12-23
相关资源
相似解决方案