标签:公司 http rabl state out att body index doctype
主要就是在没有AddOrUpdate方法的时候,你想要改变数据库内的一条数据如何操作
核心操作(这里主要展示下如何只改变一个字段“ShipName”的值)
(改变整条记录的值在Attach后面操作db.Entry(order).State = EntityState.Modified;然后savechange即可,但是注意这样操作是将新建的order对象对应的字段全部替换了)
[HttpPost] public ActionResult Edit() { int orderID = int.Parse(HttpContext.Request["orderID"]); string shipName = HttpContext.Request["shipname"]; Orders order = new Orders { OrderID = orderID,ShipName = shipName }; db.Set<Orders>().Attach(order); db.Entry(order).Property("ShipName").IsModified = true; db.Entry(order).Property("ShipName").CurrentValue = shipName; db.SaveChanges(); return Redirect("/Orders/Edit/?id="+orderID); }
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using T1_EF.Models; namespace T1_EF.Controllers { public class OrdersController : Controller { DbContext db = new NorthwindEntities(); // GET: Orders public ActionResult Index() { var list = from order in db.Set<Orders>() select order; ViewData.Model = list; return View(); } public ActionResult Edit(int id) { var data = db.Set<Orders>().Where(o=>o.OrderID==id).FirstOrDefault(); ViewData.Model = data; return View(); } [HttpPost] public ActionResult Edit() { int orderID = int.Parse(HttpContext.Request["orderID"]); string shipName = HttpContext.Request["shipname"]; Orders order = new Orders { OrderID = orderID,ShipName = shipName }; db.Set<Orders>().Attach(order); db.Entry(order).Property("ShipName").IsModified = true; db.Entry(order).Property("ShipName").CurrentValue = shipName; db.SaveChanges(); return Redirect("/Orders/Edit/?id="+orderID); } } }
前台代码Index.cshtml:
@model IEnumerable<T1_EF.Models.Orders> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <table border="1"> <tr> <td>订单编号</td> <td>客户名称</td> <td>船舶公司</td> <td>船名</td> <td>修改</td> </tr> @foreach (var item in Model) { <tr> <td>@item.OrderID</td> <td>@item.Customers.CompanyName</td> <td>@item.Shippers.CompanyName</td> <td>@item.ShipName</td> <td><a href="@Url.Action("Edit","Orders")?id=@item.OrderID">修改</a></td> </tr> } </table> </div> </body> </html>
Edit.cshtml:
@model T1_EF.Models.Orders @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Edit</title> </head> <body> <div> <table border="1"> <tr> <td>@Model.OrderID</td> <td>@Model.Customers.CompanyName</td> <td>@Model.Shippers.CompanyName</td> <td>@Model.ShipName</td> </tr> </table> <form action="@Url.Action("Edit","Orders")" method="post"> <input type="hidden" name="orderID" value="@Model.OrderID"/> <input type="text" name="shipname" placeholder="修改ShipName的值" /> <input type="submit" name="change" value="修改ShipName" /> </form> </div> </body> </html>
End
标签:公司 http rabl state out att body index doctype
原文地址:https://www.cnblogs.com/LeeSki/p/12267030.html