添加Action DeleteUserInfo
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplicationStudy.Models; namespace MvcApplicationStudy.Controllers { public class UserInfoController : Controller { // // GET: /UserInfo/ public ActionResult Index() { TestEntities db = new TestEntities(); var userInfoList = db.UserInfo.Where<UserInfo>(c => true); List<UserInfo> list = userInfoList.ToList(); // ViewBag.Model = list; //return View(); return View(list); } //展示一条数据详细信息 public ActionResult ShowDetail(int id) { TestEntities db = new TestEntities(); UserInfo userInfo = db.UserInfo.Where<UserInfo>(u => u.ID == id).SingleOrDefault(); if (userInfo != null) { return View(userInfo); } else { return Content("参数错误"); } } public ActionResult EditUserInfo(int id) { TestEntities db = new TestEntities(); UserInfo userInfo = db.UserInfo.Where<UserInfo>(u => u.ID == id).FirstOrDefault(); if (userInfo != null) return View(userInfo); else return Content("参数错误"); } [HttpPost] public ActionResult EditUserInfo(UserInfo userInfo) { TestEntities db = new TestEntities(); db.Entry<UserInfo>(userInfo).State = System.Data.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult DeleteUserInfo(int id) { TestEntities db = new TestEntities(); UserInfo userInfo = db.UserInfo.Where<UserInfo>(u => u.ID == id).SingleOrDefault(); if (userInfo != null) { db.Entry<UserInfo>(userInfo).State = System.Data.EntityState.Deleted; db.SaveChanges(); return RedirectToAction("Index"); } else { return Content("删除失败"); } } } }
修改Index视图如下:
@model IEnumerable<MvcApplicationStudy.Models.UserInfo> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <script src="~/Scripts/jquery-1.7.1.js"></script> <script type="text/javascript"> $(function () { var dels = $(".del"); for (var i = 0; i < dels.length; i++) { dels[i].onclick = function () { return confirm("您确定要删除吗?"); }; } }); </script> <title>Index</title> </head> <body> <div> <table> <tr><th>编号</th><th>用户名</th><th>密码</th><th>时间</th><th>详细</th><th>删除</th><th>修改</th></tr> @* @foreach(var userInfo in ViewBag.Model){ <tr> <td>@userInfo.ID</td> <td>@userInfo.UserName</td> <td>@userInfo.UserPwd</td> <td>@userInfo.RegTime</td> <td>详细</td> <td>删除</td> <td>修改</td> </tr> }*@ @foreach(var item in Model){ <tr> <td>@Html.DisplayFor(modelItem=>item.ID)</td> <td>@Html.DisplayFor(modelItem=>item.UserName)</td> <td>@Html.DisplayFor(modelItem=>item.UserPwd)</td> <td>@Html.DisplayFor(modelItem=>item.RegTime)</td> <td>@Html.ActionLink("详细", "ShowDetail", new{ id=item.ID})</td> <td>@Html.ActionLink("删除", "DeleteUserInfo", new { id = item.ID }, new { @class="del"})</td> <td>@Html.ActionLink("修改", "EditUserInfo", new { id=item.ID})</td> </tr> } </table> </div> </body> </html>
运行结果:
点击确定,该条记录就被删除了
时间: 2024-11-11 00:15:14