我有一个主要的Contact和ContactViewModel。如何获取联系人模型并将其更新到数据库?
[HttpPost]
public ActionResult EditContact(ContactFormViewModel contactView) {
}
在我需要ViewModel
之前,我这样做了[HttpPost]
public ActionResult EditContact(int id, FormCollection collection) {
Contact contact = repository.GetContactById(id);
if (TryUpdateModel(contact, "Contact")) {
repository.Save();
return RedirectToAction("Index");
return View(new ContactFormView Model(contact));
}
}
答案 0 :(得分:1)
拥有视图模型会更容易(您可以忘记FormCollection
和TryUpdateModel
):
[HttpPost]
public ActionResult EditContact(ContactViewModel contact)
{
if (ModelState.IsValid)
{
// the model is valid => we can save it to the database
Contact contact = mapper.Map<ContactViewModel, Contact>(contact);
repository.Save(contact);
return RedirectToAction("Index");
}
// redisplay the form to fix validation errors
return View(contact);
}
其中mapper
在视图模型和模型之间进行转换。 AutoMapper是完成此任务的绝佳选择。