在这种情况下,您需要做的就是将您正在编辑的实体的 ID 作为隐藏字段以及您实际想要编辑的属性的文本字段包含在内:
@using (Html.BeginForm())
{
@Html.HiddenFor(x => x.ID)
@Html.EditorFor(x => x.PropertyYouWannaEdit)
<button type="submit">Update</button>
}
然后在相应的控制器操作中,您可以从数据库中检索需要编辑的实体,更新需要编辑的属性的值并保存更改。
[HttpPost]
public ActionResult Update(SomeEntity model)
{
SomeEntity entityToEdit = db.GetEntity(model.ID);
entityToEdit.PropertyYouWannaEdit = model.PropertyYouWannaEdit;
db.Update(entityToEdit);
return RedirectToAction("Success");
}
但就我个人而言,我会使用视图模型自动映射器来处理这种情况。因此,我首先设计一个代表视图要求的视图模型,并包含仅需要编辑的属性:
public class MyEntityViewModel
{
public int ID { get; set; }
public string Property1ToBeEdited { get; set; }
public string Property2ToBeEdited { get; set; }
...
}
然后就有相应的视图:
@model MyEntityViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(x => x.ID)
@Html.EditorFor(x => x.Property1ToBeEdited)
@Html.EditorFor(x => x.Property2ToBeEdited)
...
<button type="submit">Update</button>
}
最后是 2 个控制器操作(GET 和 POST):
public ActionResult Update(int id)
{
// Fetch the domain model that we want to be edited from db
SomeEntity domainModel = db.GetEntity(id);
// map the domain model to a view model
MyEntityViewModel viewModel = Mapper.Map<SomeEntity, MyEntityViewModel>(domainModel);
// pass the view model to the view
return View(viewModel);
}
[HttpPost]
public ActionResult Update(MyEntityViewModel model)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay view so that the user can fix the errors
return View(model);
}
// fetch the domain entity that needs to be edited:
SomeEntity entityToEdit = db.GetEntity(model.ID);
// update only the properties that were part of the view model,
// leaving the others intact
Mapper.Map<MyEntityViewModel, SomeEntity>(model, entityToEdit);
// persist the domain model
db.Update(entityToEdit);
// we are done
return RedirectToAction("Success");
}