你的位置:首页 > ASP.net教程

[ASP.net教程]webapi初学项目(增删改查)


初学wenapi做了一个从数据库增删改查的项目

webapi

 1.创建项目:visual C# —> ASP.NET MVC 4 web应用程序 模板—>web api;

 

   

2.注册路由:

  

  路由表中的每一个条目都包含一个路由模板。这个Web API默认的路由模版是"api/{controller}/{id}"。在这个模版中,“api”是一个文字式路径片段,而{controller}和{id}则是占位符变量。

  当Web API框架接收一个HTTP请求时,它会试图根据路由表中的一个路由模板来匹配其URI。如果无路由匹配,客户端会接收到一个404(未找到)错误。

3.linq to sql连接数据库

  1.建立数据库建表

  2.在models文件夹里面新建linq to sql类文件

  3.工具->连接到数据库

  4.将要用的表拖入设计区

  

5.获取数据库Getway。"linq to sql class"文件名+Datacontext实例化这个对象,数据表就会映射到一个集合属性中,personDataDataContext db = new personDataDataContext();

6.增删改查

  

  public Boolean Post([FromBody]UserInfo userInfo)   {   

    personDataDataContext db = new personDataDataContext();

    var s1 = new test2   

    {   

      UserName =userInfo.UserName,   Id=userInfo.Id,   Age=userInfo.Age   

    };

    if (db.test2.SingleOrDefault<test2>(s => s.Id == userInfo.Id) == null)   

      {   

        db.test2.InsertOnSubmit(s1);   

        db.SubmitChanges();   

        return true;   

      }   else {   

        return false;   

      }
  }

  :

  public bool Delete(int id)   

  {   

    personDataDataContext db = new personDataDataContext();   

    var deleteperson = db.test2.SingleOrDefault<test2>(s => s.Id == id);   

    if (deleteperson == null)   

    {   

      return false;   

    }   else {   

       db.test2.DeleteOnSubmit(deleteperson);   

       db.SubmitChanges();   

       return true;   

      }
    }

  :    

  public Boolean Put(int id, [FromBody]UserInfo userInfo)   

  {   

    personDataDataContext db = new personDataDataContext();   

    var editperson = db.test2.SingleOrDefault<test2>(s => s.Id == userInfo.Id);   

    if (editperson == null)   

    {   

      return false;   

    }   else {   

       editperson.Age = userInfo.Age;   

       editperson.UserName = userInfo.UserName;   

       db.SubmitChanges();   

       return true;   

    }   

  查:

  public IEnumerable<test2> Get()   

  {   

    personDataDataContext db = new personDataDataContext();   

    var query = from s in db.test2   

    orderby s.UserName   

    select s;   

    return query;   

  }

  // GET api/values/5   

  public string Get(int id)   

  {   

    return "value";   

  }

  这里我新建了一个userinfo类

   public class UserInfo   {     public string UserName { get; set; }     public int Id { get; set; }     public int Age { get; set; }   }

  用来接收前端页面ajax请求中的data数据,s => s.Id == userInfo.Id是lamda表达式创建委托方法意思是在db.test2的person集合中查找某个person的Id与userinfo接收到的id相等的person对象

 

前端页面部分

  

@{     Layout = null; }

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>index</title>

    <link href="~/CSS/bootstrap.css" rel="stylesheet" />

    <script src="~/Scripts/jquery-1.11.3.min.js"></script>

    <script src="~/Scripts/bootstrap.js"></script>

    <script src="~/Scripts/sweetalert-dev.js"></script>    

    <script src="~/Scripts/sweetalert.min.js"></script>    

    <script src="~/Scripts/table.js"></script>    

    <link href="~/CSS/sweetalert.css" rel="stylesheet" />

    <link href="~/CSS/table.css" rel="stylesheet" />

</head>

<body>

    <div>

        <input type="button" data-toggle="modal" href="#modal-login" value="增加" />

    </div>

    <table id="table" >

        <thead>

            <tr >

                <th>用户名</th>

                <th>工号</th>

                <th>年龄</th>

                <th>操作</th>

            </tr>

        </thead>

       <tbody></tbody>

    </table>

    <!---------------------------------------------模态框------------------------------------------------>

    <div id="modal-login" >

        <!--半透明遮罩-->

        <div >

            <!--宽、定位-->

            <div >

                <!--背景色、边框、阴影-->

                <div >

                    <span data-dismiss="modal" >&times;</span>

                    <h3 >用户信息添加</h3>

                </div>

                <div >

                    <form>

                        <div >

                            <label for="uname">用户名:</label>

                            <input id="uname" type="text" />

                        </div>

                        <div >

                            <label for="uid">工号:</label>

                            <input id="uid" type="text" />

                        </div>

                        <div >

                            <label for="upwd">年龄:</label>

                            <input id="uage" type="text" />

                        </div>

                    </form>

                </div>

                <div >

                    <input id="submitData" type="button" value="提交" />

                    <input id="cancel" data-dismiss="modal" type="button" value="取消" />

                </div>

            </div>

        </div>

    </div>

</body>

</html>

 

 

js文件:

$(function () {

    $.ajax({

        type: "GET",

        url: "/api/Values",

        data: {},

        success: function (data) {

            for (var i = 0; i < data.length; i++) {

                var $info = $("<tr><td>" + data[i].UserName + "</td><td>" + data[i].Id + "</td><td>" + data[i].Age + "</td><td><input type='button' class='btn btn-warning btn-lg' id='btnPutUserInfo' data-toggle='modal' href='#modal-login' href='#modal-login' value='修改' /><input type='button' class='btn btn-danger btn-lg delete' value='删除'/></td></tr>");

                $("#table>tbody").append($info);

            }

        }

    })

    //绑定post按钮点击事件 $("#submitData").click(function (e) {

        if (e.target.value !== '修改') { console.log(e.target.value !== '修改'); console.log(e.target.value)

            var uname = document.getElementById("uname");

            var uid = document.getElementById("uid");

            var uage = document.getElementById("uage");

            if (uid.value === null) { return false }

            $.ajax({

                type: "POST",

                url: "/api/Values",

                data: { "Id": uid.value, "Age": uage.value, "UserName": uname.value },

                success: function (data) {

                    if (data == true) {

                        swal("添加成功!","", "success");

                    } else {

                        swal("添加失败!","","error");

                    }
                    $(".confirm").click(function () { window.location.reload(); })

                }

            })

        }

    })

    //绑定修改和删除事件 $("table").on('click', function (e) {

        if (e.target.value == '删除') { swal({

                title: "您确定要删除吗?", text: "您确定要删除这条数据?", type: "warning",

                showCancelButton: true,

                closeOnConfirm: false,

                confirmButtonText: "是的,我要删除", confirmButtonColor: "#ec6c62"

            }, function() {

                $.ajax({

                    type: "DELETE",

                    url: "/api/Values/" + e.target.parentNode.parentNode.firstChild.nextSibling.innerHTML,

                    data: {},

                }).done(function (data) {

                    swal("操作成功!", "已成功删除数据!", "success");

                    $(".confirm").click(function () { window.location.reload(); })

                }).error(function(data) {

                    swal("OMG", "删除操作失败了!", "error");

                    $(".confirm").click(function () { window.location.reload(); })

                });
            });

        } else if (e.target.value == '修改') {

      try { $("#submitData")[0].id = "submitChange" }

                catch (e) { };

                $("form div:nth-child(2)").remove();

                $("#submitChange")[0].value = '修改'; var uname = document.getElementById("uname");

                var uage = document.getElementById("uage");

                var age = e.target.parentNode.previousSibling;

                var id = age.previousSibling;

                var name = id.previousSibling;

                uage.value = age.innerHTML//年龄 uname.value = name.innerHTML//用户名
      $("h3")[0].innerHTML = "用户信息修改"

                $("#submitChange").click(function () {

                    console.log(id.innerHTML);

                    $.ajax({

                        type: "PUT",

                        url: "/api/Values/" + id.innerHTML,

                        data: { "Id": id.innerHTML, "Age": uage.value, "UserName": uname.value },

                        success: function (data) {

                            if (data == true) {

                                swal("修改成功!","", "success");

                            } else {

                                swal("修改失败!","", "error");

                            }

                            $(".confirm").click(function () { window.location.reload(); })

                        }

                    })

                })

                $("#cancel").click(function () { window.location.reload();  })
        }
    })
})

前端截图:

  

       

css对表格做了些样式处理我就不贴出来了,这里我用了一个弹窗的jquery插件叫sweetalert.js所有里面有swal这个方法调用。说一下前端页面我主要遇到的问题:

前端我在页面加载后执行Get方法获取数据库中的所有记录。通过遍历拼接字符串加载表格和按钮。

1.在对按钮绑定事件的时候我发现修改和删除按钮绑定的事件不能被触发可能是由于这两个按钮是生成的按钮不能绑定click事件,于是我先绑定原先的table,再用e.target获取事件对象,对事件对象进行判断,执行修改或删除命令。

2.在修改时因为我添加事件也使用了之前那个模态框导致我做修改的时候程序是走到了绑定添加的事件里面的,为了将这两个事件区别开,我在put方法下先修改了提交按钮的id,在绑定这个新的id的按钮事件来解决这个问题。

 

大致的经过就是这样,之前一直是做的前端这一块,对.net才刚刚接触,这是我的第一篇文章,后面我还会将我学习的东西分享给大家,如果有什么地方做的不好的也欢迎大家给予指正!