ASP.NET Web API教程(三) 增删改

   上一篇中已经介绍了如何获取数据,这一篇就直接分享增删改。

第一步增加方法
Bll中增加

public UserInfo Add(UserInfo user)
        {
            var tempId = Data.OrderByDescending(j => j.Id).First().Id + 1;
            user.Id = tempId;
            Data.Add(user);
            return user;
        }

        public UserInfo Update(UserInfo user)
        {
            var tempUser = Data.Where(j => j.Id == user.Id).Single();
            tempUser.Age = user.Age;
            tempUser.Name = user.Name;
            return tempUser;
        }

        public bool TryGet(int id, out UserInfo user)
        {
            try
            {
                user = Data.Where(j => j.Id == id).Single();
                return true;
            }
            catch (Exception)
            {
                user = null;
                return false;
            }
        }

        public void Delete(int id)
        {
            Data.Remove(Data.Where(j => j.Id == id).Single());
        }

以上为增删改方法

第二步 增加Controller中方法

// add
        public HttpResponseMessage Post(UserInfo userInfo)
        {
            userInfo = bll.Add(userInfo);
            var response = Request.CreateResponse<UserInfo>(HttpStatusCode.Created, userInfo);
            response.Headers.Location = new Uri(Request.RequestUri, "/api/userinfo/" + userInfo.Id.ToString());
            return response;
        }


        //post update
        public HttpResponseMessage Update(int id,UserInfo userInfo)
        {
            userInfo = bll.Update(userInfo);
            var response = Request.CreateResponse<UserInfo>(HttpStatusCode.OK, userInfo);
            response.Headers.Location = new Uri(Request.RequestUri, "/api/userinfo/" + userInfo.Id.ToString());
            return response;
        }

        // DELETE
        public UserInfo Delete(int id)
        {
            UserInfo user;
            if (!bll.TryGet(id, out user))
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            bll.Delete(id);
            return user;

        }


第三步准备页面新建页面
首先引入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>


增加操作代码

<a class="delete" data-bind="attr: { 'data-userinfo-id': Id }" href="#">删除</a>
                <a class="update" data-bind="attr: { 'data-userinfo-id': Id,'data-userinfo-name': Name,'data-userinfo-age': Age }" href="#">修改</a>

添加或修改Form

<form id="newUserInfoForm">
        <fieldset>
            <legend>新建</legend>
            <input type="hidden" value="0" name="id" id="id" />
            <label for="text">名称</label>
            <input id="name" name="name" type="text" value="" />
            <label for="text">年龄</label>
            <input id="age" name="age" type="text" value="" />
            <button type="submit">Submit</button>
        </fieldset>
        </form>

完善js功能

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

            ko.applyBindings(viewModel);
            $.get(
'/api/userInfo', function (data) {
               
// 从API中
                // 得到返回的数据,更新 Knockout 模型并且绑定到页面UI模板中                        
                viewModel.userinfos(data);
            });

            $(
'#newUserInfoForm').submit(function () {
               
var form = $(this);
               
var userinfo = { Id: $("#id").val(), Name: $('#name').val(), Age: $('#age').val() };
               
var json = JSON.stringify(userinfo);
               
if ($("#id").val() == "0") {
                    $.ajax({
                        url:
'/api/userinfo',
                        cache:
false,
                        type:
'POST',
                        data: json,
                        contentType:
'application/json; charset=utf-8',
                        statusCode: {
                           
201 /*Created*/: function (data) {
                                viewModel.userinfos.push(data);
                            }
                        }
                    });
                }
else {
                    $.ajax({
                        url:
'/api/userinfo/' + $("#id").val(),
                        cache:
false,
                        type:
'POST',
                        data: json,
                        contentType:
'application/json; charset=utf-8',
                        statusCode: {
                           
200 /*Update*/: function (data) {
                                viewModel.userinfos.remove(
function (userinfo) {
                                   
return userinfo.Id == data.Id;
                                });
                                viewModel.userinfos.push(data);

                            }
                        }
                    });
                }
               
return false;
            });
            $(
"a.update").live('click', function () {
                $(
"#id").val($(this).data('userinfo-id'));
                $(
"#name").val($(this).data('userinfo-name'));
                $(
"#age").val($(this).data('userinfo-age'));
            });
            $(
"a.delete").live('click', function () {
               
var id = $(this).data('userinfo-id');

                $.ajax({
                    url:
"/api/userinfo/" + id,
                    type:
'DELETE',
                    cache:
false,
                    statusCode: {
                       
200: function (data) {
                            viewModel.userinfos.remove(
function (userinfo) {
                               
return userinfo.Id == data.Id;
                            });
                        }
                    }
                });

               
return false;
            });
       
</script>


接下来就是激动人心的时候了,测试功能。

以下为本章的源码:/Files/risk/web api3/MvcApplication1.rar

posted @ 2012-08-24 16:52  西瓜小强  阅读(10087)  评论(5编辑  收藏  举报