实体类:

    using System;
using System.Collections.Generic; public partial class EmployeeInfo
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public string DeptName { get; set; }
public string Designation { get; set; }
public decimal Salary { get; set; }
}

控制器:

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.Http;
using System.Web.Http.Description;
using MVC5_Editable_Table.Models; namespace MVC5_Editable_Table.Controllers
{
public class EmployeeInfoAPIController : ApiController
{
private ApplicationEntities db = new ApplicationEntities(); // GET api/EmployeeInfoAPI
public IQueryable<EmployeeInfo> GetEmployeeInfoes()
{
return db.EmployeeInfoes;
} // GET api/EmployeeInfoAPI/5
[ResponseType(typeof(EmployeeInfo))]
public IHttpActionResult GetEmployeeInfo(int id)
{
EmployeeInfo employeeinfo = db.EmployeeInfoes.Find(id);
if (employeeinfo == null)
{
return NotFound();
} return Ok(employeeinfo);
} // PUT api/EmployeeInfoAPI/5
public IHttpActionResult PutEmployeeInfo(int id, EmployeeInfo employeeinfo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} if (id != employeeinfo.EmpNo)
{
return BadRequest();
} db.Entry(employeeinfo).State = EntityState.Modified; try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeInfoExists(id))
{
return NotFound();
}
else
{
throw;
}
} return StatusCode(HttpStatusCode.NoContent);
} // POST api/EmployeeInfoAPI
[ResponseType(typeof(EmployeeInfo))]
public IHttpActionResult PostEmployeeInfo(EmployeeInfo employeeinfo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} db.EmployeeInfoes.Add(employeeinfo);
db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = employeeinfo.EmpNo }, employeeinfo);
} // DELETE api/EmployeeInfoAPI/5
[ResponseType(typeof(EmployeeInfo))]
public IHttpActionResult DeleteEmployeeInfo(int id)
{
EmployeeInfo employeeinfo = db.EmployeeInfoes.Find(id);
if (employeeinfo == null)
{
return NotFound();
} db.EmployeeInfoes.Remove(employeeinfo);
db.SaveChanges(); return Ok(employeeinfo);
} protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
} private bool EmployeeInfoExists(int id)
{
return db.EmployeeInfoes.Count(e => e.EmpNo == id) > ;
}
}
}

视图:

@{
ViewBag.Title = "Index";
} <h2>CRUD Operationson HTML Table using HTML Templates</h2> <style type="text/css">
table {
width: 700px;
border: double;
} th {
width: 100px;
} td {
border: double;
width: 100px;
} input {
width: 100px;
}
</style>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<script src="~/Scripts/knockout-3.1.0.js"></script> <input type="button" value="Add New Record" data-bind="click: function () { EmpViewModel.addnewRecord(); }" />
<table>
<thead>
<tr>
<th>
EmpNo
</th>
<th>
EmpName
</th>
<th>
DeptName
</th>
<th>
Desigation
</th>
<th>
Salary
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody data-bind="template: { name: currentTemplate, foreach: Employees }"></tbody>
</table> <script type="text/html" id="readonlyTemplate">
@* <table>*@
<tr>
<td>
<span data-bind="text: EmpNo"></span>
</td>
<td>
<span data-bind="text: EmpName"></span>
</td>
<td>
<span data-bind="text: DeptName"></span>
</td>
<td>
<span data-bind="text: Designation"></span>
</td>
<td>
<span data-bind="text: Salary"></span>
</td>
<td>
<input type="button" value="Edit" data-bind="click: function () { EmpViewModel.editTemplate($data);}" />
</td>
<td>
<input type="button" value="delete" data-bind="click: function () { EmpViewModel.deleteEmployee($data); }" />
</td>
</tr>
@* </table>*@
</script> <script type="text/html" id="editTemplate">
@* <table>*@
<tr>
<td>
<input type="text" data-bind="value: $data.EmpNo" id="txteno" disabled="disabled" />
</td>
<td>
<input type="text" data-bind="value: $data.EmpName" id="txtename" />
</td>
<td>
<input type="text" data-bind="value: $data.DeptName" id="txtdname" />
</td>
<td>
<input type="text" data-bind="value: $data.Designation" id="txtdesig" />
</td>
<td>
<input type="text" data-bind="value: $data.Salary" id="txtsal" />
</td>
<td>
<input type="button" value="Save" data-bind="click: EmpViewModel.saveEmployee" />
</td>
<td>
<input type="button" value="Cancel" data-bind="click: function () { EmpViewModel.reset(); }" />
</td>
</tr>
@* </table>*@
</script> <script type="text/javascript"> var self = this;
//S1:Boolean to check wheather the operation is for Edit and New Record
var IsNewRecord = false; self.Employees = ko.observableArray([]); loadEmployees(); //S2:Method to Load all Employees by making call to WEB API GET method
function loadEmployees() {
$.ajax({
type: "GET",
url: "api/EmployeeInfoAPI",
success: function (data) {
alert("Success");
self.Employees(data);
},
error: function (err) {
alert(err.status + " <--------------->");
}
}); };
alert("Loading Data"); //S3:The Employee Object
function Employee(eno, ename, dname, desig, sal) {
return {
EmpNo: ko.observable(eno),
EmpName: ko.observable(ename),
DeptName: ko.observable(dname),
Designation: ko.observable(desig),
Salary: ko.observable(sal)
}
}; //S4:The ViewModel where the Templates are initialized
var EmpViewModel = {
readonlyTemplate: ko.observable("readonlyTemplate"),
editTemplate: ko.observable()
}; //S5:Method ti decide the Current Template (readonlyTemplate or editTemplate)
EmpViewModel.currentTemplate = function (tmpl) {
return tmpl === this.editTemplate() ? 'editTemplate' : this.readonlyTemplate();
}.bind(EmpViewModel); //S6:Method to create a new Blabk entry When the Add New Record button is clicked
EmpViewModel.addnewRecord = function () {
alert("Add Called");
self.Employees.push(new Employee(0, "", "", "", 0.0));
IsNewRecord = true; //Set the Check for the New Record
}; //S7:Method to Save the Record (This is used for Edit and Add New Record)
EmpViewModel.saveEmployee = function (d) { var Emp = {};
Emp.EmpNo = d.EmpNo;
Emp.EmpName = d.EmpName;
Emp.DeptName = d.DeptName;
Emp.Designation = d.Designation;
Emp.Salary = d.Salary;
//Edit teh Record
if (IsNewRecord === false) {
$.ajax({
type: "PUT",
url: "api/EmployeeInfoAPI/" + Emp.EmpNo,
data: Emp,
success: function (data) {
alert("Record Updated Successfully " + data.status);
EmpViewModel.reset();
},
error: function (err) {
alert("Error Occures, Please Reload the Page and Try Again " + err.status);
EmpViewModel.reset();
}
});
}
//The New Record
if (IsNewRecord === true) {
IsNewRecord = false;
$.ajax({
type: "POST",
url: "api/EmployeeInfoAPI",
data: Emp,
success: function (data) {
alert("Record Added Successfully " + data.status);
EmpViewModel.reset();
loadEmployees();
},
error: function (err) {
alert("Error Occures, Please Reload the Page and Try Again " + err.status);
EmpViewModel.reset();
}
});
}
}; //S8:Method to Delete the Record
EmpViewModel.deleteEmployee = function (d) { $.ajax({
type: "DELETE",
url: "api/EmployeeInfoAPI/" + d.EmpNo,
success: function (data) {
alert("Record Deleted Successfully " + data.status);
EmpViewModel.reset();
loadEmployees();
},
error: function (err) {
alert("Error Occures, Please Reload the Page and Try Again " + err.status);
EmpViewModel.reset();
}
});
}; //S9:Method to Reset the template
EmpViewModel.reset = function (t) {
this.editTemplate("readonlyTemplate");
}; ko.applyBindings(EmpViewModel);
</script>

图文介绍地址:http://www.dotnetcurry.com/showarticle.aspx?ID=1006

代码下载:https://github.com/dotnetcurry/htmltable-mvc-webapi

谢谢浏览!

代码演示用 KnockoutJS 和 Web API 对一个表格(Gird)进行 CRUD 操作,在 MVC 5 下的更多相关文章

  1. HttpActionDescriptor,ASP.NET Web API又一个重要的描述对象

    HttpActionDescriptor,ASP.NET Web API又一个重要的描述对象 通过前面对“HttpController的激活”的介绍我们已经知道了ASP.NET Web API通过Ht ...

  2. 通过Knockout.js + ASP.NET Web API构建一个简单的CRUD应用

    REFERENCE FROM : http://www.cnblogs.com/artech/archive/2012/07/04/Knockout-web-api.html 较之面向最终消费者的网站 ...

  3. HTML5 Web SQL Database 与 Indexed Database 的 CRUD 操作

    http://www.ibm.com/developerworks/cn/web/1210_jiangjj_html5db/ 版权声明:本文博客原创文章,博客,未经同意,不得转载.

  4. 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API

    原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...

  5. knockoutjs+ jquery pagination+asp.net web Api 实现无刷新列表页

    Knockoutjs 是一个微软前雇员开发的前端MVVM JS框架, 具体信息参考官网 http://knockoutjs.com/ Web API数据准备: 偷个懒数据结构和数据copy自官网实例  ...

  6. 从实体框架核心开始:构建一个ASP。NET Core应用程序与Web API和代码优先开发

    下载StudentApplication.Web.zip - 599.5 KB 下载StudentApplication.API.zip - 11.5 KB 介绍 在上一篇文章中,我们了解了实体框架的 ...

  7. 【ASP.NET MVC 5】第27章 Web API与单页应用程序

    注:<精通ASP.NET MVC 3框架>受到了出版社和广大读者的充分肯定,这让本人深感欣慰.目前该书的第4版不日即将出版,现在又已开始第5版的翻译,这里先贴出该书的最后一章译稿,仅供大家 ...

  8. 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

    由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...

  9. Web API 强势入门指南

    Web API是一个比较宽泛的概念.这里我们提到Web API特指ASP.NET Web API. 这篇文章中我们主要介绍Web API的主要功能以及与其他同类型框架的对比,最后通过一些相对复杂的实例 ...

随机推荐

  1. fir.im Weekly - 我回来了

    Hey, 大家好,距离 fir.im 新版上线已匆忙过去一周多的时间,新版的fir正在慢慢稳定优化中,感谢大家的反馈与支持!后续我们将上线 FAQ 帮助中心,如还有疑问请邮件至 help@fir.im ...

  2. LDR 和 ADR 彻底详解

    0.什么是位指令? 答:伪指令(Pseudo instruction)是用于告诉汇编程序如何进行汇编的指令.它既不控制机器的操作也不被汇编成机器代码, 只能为汇编程序所识别并指导汇编如何进行. 1.L ...

  3. javaweb回顾第四篇Servlet异常处理

    前言:很多网站为了给用户很好的用户体验性,都会提供比较友好的异常界面,现在我们在来回顾一下Servlet中如何进行异常处理的. 1:声明式异常处理 什么是声明式:就是在web.xml中声明对各种异常的 ...

  4. 在 C++Builder 工程里调用 DLL 函数

    调用 Visual C++ DLL 给 C++Builder 程序员提出了一些独特的挑战.在我们试图解决 Visual C++ 生成的 DLL 之前,回顾一下如何调用一个 C++Builder 创建的 ...

  5. 大型架构.net平台篇(WEB层均衡负载nginx)

    第一部分 WEB层均衡负载.net平台下,我目前部署过的均衡负载有两种方式(iis7和Nginx),以下以Nginx为例讲解web层的均衡负载. 简介:Nginx 超越 Apache 的高性能和稳定性 ...

  6. Revit中如何将视图过滤器传递到其它项目

    在Revit中采用过滤器控制视图显示,利用过滤器给图元着色,利用过滤器控制视图显示或隐藏等,那么,在不同的项目中是否每次都要设置相同的过滤器,其实,Revit提供了这么一种在不同项目传递信息的方式,在 ...

  7. Jmeter之JDBC Request使用方法(oracle)

    JDBC Request: 这个sampler可以向数据库发送一个jdbc请求(sql语句),它经常需要和JDBC Connection Configuration 配置元件一起配合使用. 目录: 一 ...

  8. showmessage函数里

    首先说一下,漏洞是t00ls核心群传出去的,xhming先去读的,然后我后来读的,读出来的都是代码执行,1月5日夜里11点多钟,在核心群的黑客们的要求下,xhming给了个poc,我给了个exp,确实 ...

  9. 翻译--Blazing fast node.js: 10 performance tips from LinkedIn Mobile

    1.避免使用同步代码: // Good: write files asynchronously fs.writeFile('message.txt', 'Hello Node', function ( ...

  10. 2016年象行中国(上海站)圆满结束,会议PPT分享

    2016年象行中国(上海站)已于5-21日圆满结束,所有技术交流的文档和PPT经整理后,现集中存放在云盘中,相关议题如下:     DeepGreen-LLVM-Intro.pptx ... 1.1M ...