asp.net-mvc如何更新实体框架中的一个实体

发布时间: 2017/2/21 1:19:24
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我在我的数据库中有一个日期字段,我想更新为当前日期当我按我的网页上的提交按钮,但它不会更新。我相信我做的正确的步骤,但在这里是我的代码。

控制器︰

public ActionResult TakeInventory(int? AssetNum, string owners, string locationId, string clientId)
        {
            ViewBag.LocationId = new SelectList(db.Locations, "LocationKey", "LocationName");
            ViewBag.ClientId = new SelectList(db.ClientSites, "ClientSiteKey", "ClientSiteName");
            var records = from s in db.Assets select s;
            if (AssetNum != 0)
            {
                records = records.Where(c => c.AssetKey == AssetNum);
            }

            if (!String.IsNullOrEmpty(owners))
            {
                records = records.Where(x => x.InventoryOwner.Equals(owners));
            }

            if (!String.IsNullOrEmpty(locationId))
            {
                int locnum = Convert.ToInt32(locationId);
                records = records.Where(x => x.LocationKey == locnum);
            }

            if (!String.IsNullOrEmpty(clientId))
            {
                int clinum = Convert.ToInt32(clientId);
                records = records.Where(x => x.ClientSiteKey == clinum);
            }


            else
            {
                return View(records);
            }
            return View(records);

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult TakeInventory([Bind(Include = "InventoryDate")] Asset asset)
        {
            if (ModelState.IsValid)
            {
                db.Entry(asset).State = EntityState.Modified;
                asset.InventoryDate = DateTime.Now;
                db.Assets.Add(asset);
                db.SaveChanges();
                return RedirectToAction("Index");

            }
            return View(asset);
        }

视图︰

@foreach (var items in Model)
    {
        <p>Last Inventory Date: @Html.DisplayFor(modelItem => items.InventoryDate) </p>
        <input type="submit" value="Submit" />

型号︰

public partial class Asset
    {    
public System.DateTime InventoryDate { get; set; }
    public Asset()
      {
      InventoryDate = DateTime.Now;
      }
    }

解决方法 1:

你想要再次更新之前再次检索资产实体。

例如,

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TakeInventory([Bind(Include = "InventoryDate")] Asset asset)
{
   if (ModelState.IsValid)
   {
      var entity = (from s in db.Assets where AssetNum == asset.AssetNum Select s).FirstOrDefalt();
      entity.InventoryDate = DateTime.Now;
      db.SaveChanges();
      return RedirectToAction("Index");
   }
   return View(asset);
}
官方微信
官方QQ群
31647020