Controller操作
主要简单备忘增、删、查、改的Controller一般操作方法,操作对象为Students实体、context为上下文连接
students对象包括name,age,sex信息,操作页面都是在MVC3中使用强类型、Razor模版建立的。
1、定义查询Index
- public ActionResult Index()
- {
- var list = context.Students.ToList(); // 获取students对象信息
- return View(list); // 返回list数据给Index界面
- }
2、 定义添加Controller
// GET: /Student/Create
// 用于显示添加界面
- public ActionResult Create()
- {
- return View(); // 默认视图页面为Crete.cshtml
- }
定义添加操作Action
[HttpPost] // 必须跟上表示Post请求执行submit按钮提交
- public ActionResult Create(Student student)
- {
- try
- {
- // TODO: Add insert logic here
- if (ModelState.IsValid)
- {
- context.Students.Add(student); // 附加对象student
- context.SaveChanges(); // 执行持久化操作
- return RedirectToAction("Index"); // 返回到Index页面
- }
- }
- catch
- {
- // 异常信息
- }
- return View(student);
- }
3、定义修改Controller
// 获取要修改的页面信息 默认页面为Edit.cshtml
- public ActionResult Edit(int id)
- {
- var model = context.Students.Find(id); // 根据ID查询获取修改信息
- return View(model); // 并赋值给View页面
- }
// 执行编辑操作
- [HttpPost]
- public ActionResult Edit(Student student)
- {
- // TODO: Add update logic here
- if (ModelState.IsValid)
- {
- // 会自动识别哪个属性被修改
- context.Entry(student).State = EntityState.Modified; // 标志为修改状态Modifyed,表示要修改,Detached、Added、Unchanged、Modifyed、Deleted
- int i = context.SaveChanges();
- return RedirectToAction("Index"); // 修改成功返回首页
- }
- return View(student);
- }
4、定义删除Controller
- // 获取要删除的信息 默认页面为delete.cshtml
- public ActionResult Delete(int id)
- {
- var model = context.Students.Find(id);
- return View(model);
- }
- // 执行操作方法
- [ActionName("Delete")] // 这里被定义了两个一样的Delete,所以需要用ActionName特性指定个Delete的Action
- [HttpPost]
- public ActionResult DeletePost(int id) // 定义成DeletePost,否则提示错误
- {
- try
- {
- // TODO: Add delete logic here
- var student = context.Students.Find(id);
- context.Students.Remove(student); // 移除操作
- // 变成Deleted状态
- context.SaveChanges(); // 持久化
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
- 利用Ajax删除,先修改Controller代码:
- try
- {
- // TODO: Add delete logic here
- if (Request.IsAjaxRequest())
- {
- var student = context.Students.Find(id);
- context.Students.Remove(student);
- int k = context.SaveChanges();
- return Content(k.ToString());
- }
- else
- {
- return Content("-1"); // 返回内容为-1 表示删除失败
- }
- }
- catch
- {
- return Content("-1");
- }
修改查询的页面中删除的链接、
把原来的 @Html.ActionLink("删除", "Delete", new { id=item.StudentID })
换成
- <a href="#" name="delete" sid=@item.StudentID>删除</a>
- 用jquery删除
- <script type="text/javascript">
- $().ready(function () {
- $("[name='delete']").click(function () {
- if (confirm("确定删除信息?")) {
- var sid = $(this).attr("sid");
- var trContent = $(this).parent().parent();
- $.post("Student/Delete/", { id: sid }, function (data) {
- if (data == "-1") {
- alert("删除失败");
- }
- else {
- $(trContent).remove();
- alert("删除成功");
- }
- })
- }
- })
- })
- </script>
在学习的过程中主要记录下asp.net MVC 的基本CRUD操作