knockout+MVC+webapi+sqlserver完成增删查改

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了knockout+MVC+webapi+sqlserver完成增删查改相关的知识,希望对你有一定的参考价值。

      快过年了,公司的事情较少,想着开始学习点新东西。这段时间一个项目用到了mvc和webapi,然后一直对knockout比较感兴趣,就想着用这个框架做一个小实例。数据库采用的是sqlserver。话不多说,开始进行项目的步骤。

      第一步:数据库的表创建。创建一个Employees员工表,具体字段见下图:

技术分享

        第二步:创建一个MVC项目,项目模板选择webapi。

技术分享

技术分享

第三步:在Model文件夹下新建一个ado.net实体数据模型,选择我们刚刚创建的employees的表,生成实体数据模型。

技术分享

第四步:在controller文件夹下新建一个控制器,注意是包含读写操作和视图的API控制器,如下图

技术分享

查看生成的代码如下

技术分享
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Data;
  4 using System.Data.Entity;
  5 using System.Data.Entity.Infrastructure;
  6 using System.Linq;
  7 using System.Net;
  8 using System.Net.Http;
  9 using System.Web;
 10 using System.Web.Http;
 11 using DemoWebApi.Models;
 12 
 13 namespace DemoWebApi.Controllers
 14 {
 15     public class EmployeeWebApiController : ApiController
 16     {
 17         private DemoDBEntities1 db = new DemoDBEntities1();
 18 
 19         // GET api/EmployeeWebApi
 20         public IEnumerable<Employees> GetEmployees()
 21         {
 22             return db.Employees.AsEnumerable();
 23         }
 24 
 25         // GET api/EmployeeWebApi/5
 26         public Employees GetEmployees(int id)
 27         {
 28             Employees employees = db.Employees.Find(id);
 29             if (employees == null)
 30             {
 31                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
 32             }
 33 
 34             return employees;
 35         }
 36 
 37         // PUT api/EmployeeWebApi/5
 38         public HttpResponseMessage PutEmployees(int id, Employees employees)
 39         {
 40             if (!ModelState.IsValid)
 41             {
 42                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
 43             }
 44 
 45             if (id != employees.EmployeeID)
 46             {
 47                 return Request.CreateResponse(HttpStatusCode.BadRequest);
 48             }
 49 
 50             db.Entry(employees).State = EntityState.Modified;
 51 
 52             try
 53             {
 54                 db.SaveChanges();
 55             }
 56             catch (DbUpdateConcurrencyException ex)
 57             {
 58                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
 59             }
 60 
 61             return Request.CreateResponse(HttpStatusCode.OK);
 62         }
 63 
 64         // POST api/EmployeeWebApi
 65         public HttpResponseMessage PostEmployees(Employees employees)
 66         {
 67             if (ModelState.IsValid)
 68             {
 69                 db.Employees.Add(employees);
 70                 db.SaveChanges();
 71 
 72                 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, employees);
 73                 response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = employees.EmployeeID }));
 74                 return response;
 75             }
 76             else
 77             {
 78                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
 79             }
 80         }
 81 
 82         // DELETE api/EmployeeWebApi/5
 83         public HttpResponseMessage DeleteEmployees(int id)
 84         {
 85             Employees employees = db.Employees.Find(id);
 86             if (employees == null)
 87             {
 88                 return Request.CreateResponse(HttpStatusCode.NotFound);
 89             }
 90 
 91             db.Employees.Remove(employees);
 92 
 93             try
 94             {
 95                 db.SaveChanges();
 96             }
 97             catch (DbUpdateConcurrencyException ex)
 98             {
 99                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
100             }
101 
102             return Request.CreateResponse(HttpStatusCode.OK, employees);
103         }
104 
105         protected override void Dispose(bool disposing)
106         {
107             db.Dispose();
108             base.Dispose(disposing);
109         }
110     }
111 }
View Code

里面有完整的对于实体类中表employee的增删查改操作。

第五步:创建一个空mvc的控制器,命名为EmployeeController,代码如下:

技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using DemoWebApi.Models;
 7 
 8 namespace DemoWebApi.Controllers
 9 {
10     public class EmployeeController : Controller
11     {
12         //
13         // GET: /Employee/
14         private DemoDBEntities1 db = new DemoDBEntities1();
15         public ActionResult Create()
16         {
17             ViewBag.MaxBh = GetMaxBh();
18             return View("Create");
19         }
20 
21         public int GetMaxBh()
22         {
23             var query = (from d in db.Employees select d.EmployeeID).Max();
24             return query + 1;
25         }
26     }
27 }
View Code

第六步:创建视图。代码如下:

技术分享
  1 @{
  2     ViewBag.Title = "Create";
  3 }
  4 
  5 @section scripts{
  6     <script src="~/Scripts/knockout.mapping-latest.js"></script>
  7     <script src="~/Scripts/knockout-2.2.0.js"></script>
  8     <script type="text/javascript">
  9         var maxbh = @ViewBag.MaxBh;
 10         var EmpViewModel = function () {
 11             var self = this;
 12             self.EmployeeID = ko.observable(maxbh);
 13             self.EmployeeName = ko.observable("");
 14             self.Salary = ko.observable("");
 15             self.DeptName = ko.observable("");
 16             self.Address = ko.observable("");
 17             var EmpData = {
 18                 EmployeeID: self.EmployeeID,
 19                 EmployeeName: self.EmployeeName,
 20                 Salary: self.Salary,
 21                 DeptName: self.DeptName,
 22                 Address: self.Address
 23             };
 24 
 25             //生成一个ObservableArray来存储返回的所有数据
 26             self.Employees = ko.observableArray([]);
 27             GetEmployees(); //通过ajax请求返回所有数据
 28             //保存数据
 29             self.save = function () {
 30                 //Ajax 提交到webapi保存数据
 31                 $.ajax({
 32                     type: "POST",
 33                     url: "/api/EmployeeApi",
 34                     data: ko.toJSON(EmpData),
 35                     contentType: "application/json",
 36                     success: function (data) {
 37                         alert("记录保存成功");
 38                         self.EmployeeID(data.EmployeeID);
 39                         window.location.reload();
 40                         GetEmployees();
 41                     },
 42                     error: function () {
 43                         alert("提交失败");
 44                     }
 45                 });
 46             };
 47 
 48             self.update = function () {
 49                 var url = "/api/EmployeeApi/" + self.EmployeeID();
 50                 $.ajax({
 51                     type: "PUT",
 52                     url: url,
 53                     data: ko.toJSON(EmpData),
 54                     contentType: "application/json",
 55                     success: function (data) {
 56                         alert("修改成功");
 57                         GetEmployees();
 58                     },
 59                     error: function (error) {
 60                         alert(error.status + "<!----!>" + error.statusText);
 61                     }
 62                 });
 63             };
 64 
 65             //删除操作
 66             self.deleterec = function (employee) {
 67                 $.ajax({
 68                     type: "DELETE",
 69                     url: "/api/EmployeeApi/" + employee.EmployeeID,
 70                     success: function (data) {
 71                         alert("Record Deleted Successfully");
 72                         GetEmployees();//Refresh the Table
 73                     },
 74                     error: function (error) {
 75                         alert(error.status + "<--and--> " + error.statusText);
 76                     }
 77                 });
 78             };
 79 
 80             //获取所有Employee
 81             function GetEmployees() {
 82                 //Ajax 获取所有Employee记录
 83                 $.ajax({
 84                     type: "GET",
 85                     url: "/api/EmployeeApi",
 86                     contentType: "application/json; charset=utf-8",
 87                     dataType: "json",
 88                     success: function (data) {
 89                         self.Employees(data);
 90                     },
 91                     error: function (error) {
 92                         alert(error.status + "<--and--> " + error.statusText);
 93                     }
 94                 });
 95             };
 96             //点击右侧列表某一行左侧编辑赋值
 97             self.getselectedemployee = function (employee) {
 98                 self.EmployeeID(employee.EmployeeID),
 99                 self.EmployeeName(employee.EmployeeName),
100                 self.Salary(employee.Salary),
101                 self.DeptName(employee.DeptName),
102                 self.Address(employee.Address)
103             };
104         };
105         //激活knockout
106         ko.applyBindings(new EmpViewModel());
107     </script>
108 }
109 
110 <body class="easyui-layout">
111     <form>
112         <table>
113             <tr>
114                 <td>
115                     <!--将textbox监控属性的值与ViewModel绑定 -->
116                     <table id="tbldml">
117                         <tr>
118                             <td>编号</td>
119                             <td>
120                                 <input type="text" id="txteno" data-bind="value: $root.EmployeeID" readonly="readonly"/></td>
121                         </tr>
122                         <tr>
123                             <td>名称</td>
124                             <td>
125                                 <input type="text" id="txtename" data-bind="value: $root.EmployeeName" /></td>
126                         </tr>
127                         <tr>
128                             <td>薪资</td>
129                             <td>
130                                 <input type="text" id="txtsal" data-bind="value: $root.Salary" /></td>
131                         </tr>
132                         <tr>
133                             <td>部门</td>
134                             <td>
135                                 <input type="text" id="txtdname" data-bind="value: $root.DeptName" /></td>
136                         </tr>
137                         <tr>
138                             <td>籍贯</td>
139                             <td>
140                                 <input type="text" id="txtdesig" data-bind="value: $root.Address" /></td>
141                         </tr>
142                         <tr>
143                             <!--ko控制的保存和修改按钮-->
144                             <td>
145                                 <button data-bind="click: $root.save" style="width: 100px;">保存</button></td>
146                             <td>
147                                 <button data-bind="click: $root.update" style="width: 100px;">修改</button></td>
148                         </tr>
149                     </table>
150                 </td>
151                 <td>
152                     <div class="FixedContainer">
153                         <!--控制有数据的时候显示表格-->
154                         <table data-bind="visible: Employees().length > 0">
155                             <thead>
156                                 <tr>
157                                     <td style="width: 100px;">编号</td>
158                                     <td style="width: 100px;">名称</td>
159                                     <td style="width: 100px;">薪资</td>
160                                     <td style="width: 100px;">部门</td>
161                                     <td style="width: 100px;">籍贯</td>
162                                     <td style="width: 100px;"></td>
163                                 </tr>
164                             </thead>
165                             <!--遍历所有数据-->
166                             <tbody data-bind="foreach: Employees">
167                                 <tr style="border: solid" data-bind="click: $root.getselectedemployee" id="updtr">
168                                     <td><span data-bind="text: EmployeeID" style="width: 100px;"></span></td>
169                                     <td><span data-bind="text: EmployeeName" style="width: 100px;"></span></td>
170                                     <td><span data-bind="text: Salary"></span></td>
171                                     <td><span data-bind="text: DeptName"></span></td>
172                                     <td><span data-bind="text: Address"></span></td>
173                                     <td>
174                                         <button data-bind="click: $root.deleterec">删除</button></td>
175                                 </tr>
176                             </tbody>
177                         </table>
178                     </div>
179                 </td>
180             </tr>
181         </table>
182     </form>
183 </body>
View Code

使用knockout绑定值需要引用两个js,knockout.mapping-latest.js和knockout-2.2.0.js。

第七步:修改RouteConfig.cs路由配置文件, defaults: new { controller = "Employee", action = "Create", id = UrlParameter.Optional }。这样基本的项目就完成了,运行可以查看效果。

技术分享

以上就是所有的项目内容。

以上是关于knockout+MVC+webapi+sqlserver完成增删查改的主要内容,如果未能解决你的问题,请参考以下文章

.NET webapp using knockout + webApi:我应该也保留 Razor 语法还是只使用 html 文件?

我是不是有理由使用 Knockout MVC 而不是 Knockout JS?

在 MVC 中使用 Knockout 进行文件上传

基于Bootstrap和Knockout.js的ASP.NET MVC开发实战

将 MVC 模型转换为 Knockout JS ViewModel

大规模 MVC Web 应用程序 - 使用 Knockout 和 Razor