【发布时间】:2017-01-21 16:56:20
【问题描述】:
我在模型Products 中有实体added,added_from,last_edited,last_edited_from。如果有人创建了一个新的Product,四个枚举的实体要填充对应的数据;有了这个一切都很好。如果有人正在编辑Product,则只填充last_edited 实体,但我在控制器中的方法每次都会覆盖added 实体并将其清空。
控制器方法:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product= db.Product.Find(id);
if (product== null)
{
return HttpNotFound();
}
ViewBag.Category_id = new SelectList(db.Category, "Id", "Name", product.Category_id);
return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Barcode,Name,Category_id,Comment")] Product product)
{
if (ModelState.IsValid)
{
product.last_edited = DateTime.Now;
product.last_edited_from = User.Identity.GetUserId();
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Category_id = new SelectList(db.Category, "Id", "Name", product.Category_id);
return View(product);
}
型号:
public int Id { get; set; }
public double Barcode { get; set; }
[MinLength(3)]
public string Name{ get; set; }
[ForeignKey("Category_id")]
public Category CategoryFK { get; set; }
[Required]
public int Category_id { get; set; }
public DateTime? added { get; set; }
[ForeignKey("added_from")]
public ApplicationUser added_from_User { get; set; }
public string added_from { get; set; }
public DateTime last_edited { get; set; }
[ForeignKey("last_edited_from")]
public ApplicationUser last_edited_from { get; set; }
public string last_edited_from { get; set; }
我尝试了大约 5 个小时,但没有发现对我有什么帮助
【问题讨论】:
标签: c# entity-framework asp.net-mvc-4 controller