我有一个编辑“商店”表的视图。这一切都很好,但View不会显示所有字段,当我尝试保存时,会抛出错误,说明View Post中不在的字段不能为空。好吧,当然,但不管怎么说,这些字段都不会被覆盖,View不会编辑它们。
这是我的帖子功能
[HttpPost]
public ActionResult Edit(Store storeModel) {
if (ModelState.IsValid) {
Store storeContext = database.Stores.Find(storeModel.ID);
database.Entry(storeContext).CurrentValues.SetValues(storeModel);
database.SaveChanges();
}
}
在线搜索,显然问题是MVC不知道您正在编辑哪些字段,只要将所有字段视为已编辑,即使该字段在回发中不存在。要“告诉”您在视图中编辑哪个字段,您必须执行以下操作:
//Store contextStore = new Store { ID = postBackStore.ID };
//database.Stores.Attach(contextStore );
//contextStore .Name = postBackStore.Name;
//contextStore .Address = postBackStore.Address;
//contextStore .City = postBackStore.City;
//contextStore .Postal = postBackStore.Postal;
//contextStore .Phone = postBackStore.Phone;
//contextStore .StoreNumber = postBackStore.StoreNumber;
//contextStore .IsActive = postBackStore.IsActive;
//database.Entry(contextStore).State = EntityState.Modified;
然而,这对我不起作用,因为MVC抱怨它已经跟踪Store对象并且无法创建具有相同ID的新对象。另外,我不喜欢当我在View中定义它们时如何再次定义所有字段。
无论如何,我可以将MVC保存更改仅限于View中的字段(与模型中的每个字段相对),而无需明确定义视图中的哪些字段?
答案 0 :(得分:0)
为什么不将viewmodel与参与字段一起使用?