初试konckout+webapi简单实现增删改查
前言
konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作。Knockout是一个以数据模型(data model)为基础的能够帮助你创建富文本,响应显示和编辑用户界面的JavaScript类库。任何时候如果你的UI需要自动更新(比如:更新依赖于用户的行为或者外部数据源的改变),KO能够很简单的帮你实现并且很容易维护。其作用简单来说就是声明所需的数据作为一个JavaScript 模型对象(model object),然后将DOM 元素或者模板(templates)绑定到它上面。
创建mvc4+webapi+konckout.js的简单应用程序
1、首先准备一个测试的数据库,我这以我随便创建的一个数据库为例
表结构如下图:
2、创建一个mvc程序,并在项目中添加一个以上表的ado.net实体数据模型
添加完成以后:
3、添加添加一个带读写操作的EmployeeApiController webapi控制器和用来实现增删改查的普通控制器EmployeeController
添加是注意选择是带读写操作的webapi控制器,选择好数据模型及数据库上下文,方面vs自动为我们生成读写操作。
添加完成后自动生成的完整代码:
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using Knockout.Models; namespace Knockout.Controllers { public class EmployeeApiController : ApiController { private DemoDBEntities db = new DemoDBEntities(); // GET api/EmployeeApi public IEnumerable<Employees> GetEmployees() { return db.Employees.AsEnumerable(); } // GET api/EmployeeApi/5 public Employees GetEmployees(int id) { Employees employees = db.Employees.Find(id); if (employees == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); } return employees; } // PUT api/EmployeeApi/5 public HttpResponseMessage PutEmployees(int id, Employees employees) { if (ModelState.IsValid && id == employees.EmployeeID) { db.Entry(employees).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return Request.CreateResponse(HttpStatusCode.NotFound); } return Request.CreateResponse(HttpStatusCode.OK); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } // POST api/EmployeeApi public HttpResponseMessage PostEmployees(Employees employees) { if (ModelState.IsValid) { db.Employees.Add(employees); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, employees); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = employees.EmployeeID })); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } // DELETE api/EmployeeApi/5 public HttpResponseMessage DeleteEmployees(int id) { Employees employees = db.Employees.Find(id); if (employees == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } db.Employees.Remove(employees); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return Request.CreateResponse(HttpStatusCode.NotFound); } return Request.CreateResponse(HttpStatusCode.OK, employees); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
在添加一个普通的控制器EmployeeController,并在里面添加如下方法:
public ActionResult Create() { return View("Create"); }
添加视图Create.cshtml:
首先在视图中添加对ko的引用,mapping.js是用来实现绑定viewmodel的第三方插件:
<script src="~/Scripts/knockout-2.1.0.js"></script> <script src="~/Scripts/knockout.mapping-latest.js"></script>
在body节点下添加一个form表单如下代码:
<form> <table> <tr> <td> <!--将textbox监控属性的值与ViewModel绑定 --> <table id="tbldml"> <tr> <td>编号</td> <td> <input type="text" id="txteno" data-bind="value: $root.EmployeeID" disabled="disabled" /></td> </tr> <tr> <td>名称</td> <td> <input type="text" id="txtename" data-bind="value: $root.EmployeeName" /></td> </tr> <tr> <td>薪资</td> <td> <input type="text" id="txtsal" data-bind="value: $root.Salary" /></td> </tr> <tr> <td>部门</td> <td> <input type="text" id="txtdname" data-bind="value: $root.DeptName" /></td> </tr> <tr> <td>籍贯</td> <td> <input type="text" id="txtdesig" data-bind="value: $root.Address" /></td> </tr> <tr> <!--ko控制的保存和修改按钮--> <td> <button data-bind="click :$root.save">保存</button></td> <td> <button data-bind="click: $root.update">修改</button></td> </tr> </table> </td> <td> <div class="FixedContainer"> <!--控制有数据的时候显示表格--> <table data-bind="visible: Employees().length>0"> <thead> <tr> <td>编号</td> <td>名称</td> <td>薪资</td> <td>部门</td> <td>籍贯</td> <td></td> </tr> </thead> <!--遍历所有数据-> <tbody data-bind="foreach: Employees"> <tr style="border: solid" data-bind="click: $root.getselectedemployee" id="updtr"> <td><span data-bind="text: EmployeeID"></span></td> <td><span data-bind="text: EmployeeName"></span></td> <td><span data-bind="text: Salary"></span></td> <td><span data-bind="text: DeptName"></span></td> <td><span data-bind="text: Address"></span></td> <td> <button data-bind="click: $root.deleterec">Delete</button></td> </tr> </tbody> </table> </div> </td> </tr> </table> </form>
4、页面改造好以后,编写Ko需要的js来实现增删改查
在页面添加scripts占位节点添加如下脚本:
@section scripts{ <script type="text/javascript"> var EmpViewModel = function () { var self = this; self.EmployeeID = ko.observable("0"); self.EmployeeName = ko.observable(""); self.Salary = ko.observable(""); self.DeptName = ko.observable(""); self.Address = ko.observable(""); var EmpData = { EmployeeID: self.EmployeeID, EmployeeName: self.EmployeeName, Salary: self.Salary, DeptName: self.DeptName, Address: self.Address }; //生命一个ObservableArray来存储返回的所有数据 self.Employees = ko.observableArray([]); GetEmployees(); //通过ajax请求返回所有数据 //保存数据 self.save = function () { //Ajax 提交到webapi保存数据 alert(11); $.ajax({ type: "POST", url: "/api/EmployeeApi", data: ko.toJSON(EmpData), contentType: "application/json", success: function (data) { alert("记录保存成功"); self.EmployeeID(data.EmployeeID); alert("新数据Id :" + self.EmployeeID()); GetEmployees(); }, error: function () { alert("提交失败"); } }); }; self.update = function () { var url = "/api/EmployeeApi/" + self.EmployeeID(); alert(url); $.ajax({ type: "PUT", url: url, data: ko.toJSON(EmpData), contentType: "application/json", success: function (data) { alert("修改成功"); GetEmployees(); }, error: function (error) { alert(error.status + "<!----!>" + error.statusText); } }); }; //删除操作 self.deleterec = function (employee) { $.ajax({ type: "DELETE", url: "/api/EmployeeApi/" + employee.EmployeeID, success: function (data) { alert("Record Deleted Successfully"); GetEmployees();//Refresh the Table }, error: function (error) { alert(error.status + "<--and--> " + error.statusText); } }); }; //获取所有Employee function GetEmployees() { //Ajax 获取所有Employee记录 $.ajax({ type: "GET", url: "/api/EmployeeApi", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { self.Employees(data); }, error: function (error) { alert(error.status + "<--and--> " + error.statusText); } }); } //点击右侧列表某一行左侧编辑赋值 self.getselectedemployee = function (employee) { self.EmployeeID(employee.EmployeeID), self.EmployeeName(employee.EmployeeName), self.Salary(employee.Salary), self.DeptName(employee.DeptName), self.Address(employee.Address) }; }; //激活knockout ko.applyBindings(new EmpViewModel()); </script> }
代码中有比较详细的注释,其中实现的增删查改的操作是通过ajax异步调用webapi来实现的,刷新及数据绑定是通过ko来实现的。
5、运行程序得到如下效果:
新增记录的时候id默认为0,表单数据为空,点击保存实现无刷新保存,右侧若无数据表格则隐藏,若有数据表格显示数据列表。
点击某一行数据,左侧表单显示该行数据信息,并可以修改信息
点击删除实现无刷新删除数据记录。