当前位置:首页 > Web开发 > 正文

数据库数据:Northwind中的Region表 Region类是根据Region表自动生成的 后台代码: using

2024-03-31 Web开发

数据库数据: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[email protected]("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[email protected]("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

MVC初体验-EF系列(CRUD)(20)

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30477.html