数据库数据:Northwind中的Region表
Region类是根据Region表自动生成的
后台代码:
using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Web.Mvc; using T1_EF.Models; namespace T1_EF.Controllers { public class RegionController : Controller { DbContext db = new NorthwindEntities(); // GET: Region public ActionResult Index() { var list = db.Set<Region>(); ViewData.Model = list; return View(); } [HttpPost] public ActionResult Add()//新增 { int regionID = int.Parse(HttpContext.Request["regionID"]); string regionDes = HttpContext.Request["regionDes"]; Region regData = new Region { RegionID = regionID, RegionDescription = regionDes }; db.Set<Region>().Add(regData); db.SaveChanges();//如果内存中的数据发生了改变,并且希望将变化映射到数据库中,需要执行保存。 return Redirect(Url.Action("Index","Region")); } [HttpPost] public ActionResult Edit()//编辑 { int regionID = int.Parse(HttpContext.Request["regionID"]); string regionDes = HttpContext.Request["regionDes"]; Region region = new Region { RegionID = regionID, RegionDescription = regionDes }; db.Set<Region>().AddOrUpdate(region);//该方法需要引用Data.Entity中的Migrations db.SaveChanges(); return Redirect("/Region/Index"); } public ActionResult Delete()//删除 { //根据HttpContext上下文对象查询出前台表单提交的数据 int regionID = int.Parse(HttpContext.Request["regionID"]); //查询出要删除的对象 var data = db.Set<Region>().FirstOrDefault(r => r.RegionID == regionID); db.Set<Region>().Remove(data); db.SaveChanges(); return Redirect(Url.Action("Index", "Region")); } } }
前台代码:
@model IEnumerable<T1_EF.Models.Region> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <table border="1"> @foreach (var item in Model) { <tr> <td>@item.RegionID</td> <td>@item.RegionDescription</td> </tr> } </table> <hr /> <form action="@Url.Action("Add","Region")" method="post"> <span>区域ID:</span> <input type="text" name="regionID" value="" /> <span>区域:</span> <input type="text" name="regionDes" value="" /> <input type="submit" name="" value="新增" /> </form> <hr /> @*这里的表单不能用put提交方法*@ <form action=@Url.Action("Edit","Region") method="post"> <span>区域ID:</span> <input type="text" name="regionID" placeholder="填写要修改数据的ID" /> <span>区域:</span> <input type="text" name="regionDes" value="" /> <input type="submit" name="change" value="修改" /> </form> <hr /> <form action=@Url.Action("Delete","Region") method="post"> <span>区域ID:</span> <input type="text" name="regionID" placeholder="填写要删除数据的ID" /> <input type="submit" name="change" value="删除" /> </form> </div> </body> </html>
显示效果:
End