KnocKout 绑定数据

时间:2021-05-22 17:50:26

KnocKout 绑定数据

Controller 里面的方法:

 public ActionResult Index()
{ return View();
}
[HttpPost]
public JsonResult Reader()
{
var list = from a in db.employee
select new
{
Id=a.e_id,
No=a.e_no,
Name=a.e_name,
Dname=a.department.d_name,
Desc=a.e_desc,
Question=a.e_question,
Anawser=a.e_answer,
Qx=a.e_qx,
Up=a.e_up };
return Json(list, JsonRequestBehavior.AllowGet);
} //删除
[HttpPost]
public JsonResult Del(int id)
{
var emp= db.employee.ToList().Find(a => a.e_id == id);
db.employee.Remove(emp);
db.SaveChanges();
return Json(new {type = "success"});
}

html页面:

 @using Knockout.Models
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
<title>Index</title>
<script type="text/javascript">
var data;
$(function() {
$.ajax({
url: "/Kn/Reader",
type: "post",
async: false,
success: function (msg) {
$.each(msg, function(x, y) {
if (y.Qx == 3) {
y.Qx = "最高权限";
}else if (y.Qx == 1) {
y.Qx = "一般权限";
} else {
y.Qx = "没有权限";
}
if (y.Up == 1) {
y.Up = "已修改";
} else {
y.Up = "未修改";
}
});
data = msg;
}
});
}); function ViewModel() {
var self = this;
self.employees = ko.observableArray(data);
//删除
self.remove= function(emp) {
$.ajax({
url: "/Kn/Del/" + emp.Id,
type: "post",
dataType: "json",
success:function(json) {
self.employees.remove(emp);
}
});
}
//编辑
self.edit = function (emp) {
window.location.href = '/Kn/edit/' + emp.Id;
};
} $(function () { var vm = new ViewModel();
ko.applyBindings(vm);
$("a:contains('删除')").click(function() {
if (confirm("是否确定要删除?")) {
return true;
} else {
return false;
}
});
}); </script>
</head>
<body>
<table width="760px" border="1px" cellpadding="0" cellspacing="0">
<tr>
<th>编号</th>
<th>姓名</th>
<th>部门名称</th>
<th>职称</th>
<th>问题</th>
<th>答案</th>
<th>权限</th>
<th>是否修改过密码</th>
<th>操作</th>
</tr>
<tbody data-bind="foreach: employees">
<tr>
<td data-bind="text:No"></td>
<td data-bind="text:Name"></td>
<td data-bind="text:Dname"></td>
<td data-bind="text:Desc"></td>
<td data-bind="text:Question"></td>
<td data-bind="text:Anawser"></td>
<td data-bind="text:Qx"></td>
<td data-bind="text:Up"></td>
<td><a href="javascript:" data-bind="click:$root.remove">删除</a>
<a href="javascript:" data-bind="click:$root.edit">修改</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>