Reputation:
I have a main Contact and ContactViewModel . How do I get contact model and update it to the database ?
[HttpPost]
public ActionResult EditContact(ContactFormViewModel contactView) {
}
I was doing like this before I needed 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));
}
}
Upvotes: 0
Views: 624
Reputation: 1039110
It's a bit easier when you have a view model (you can forget about FormCollection
and 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);
}
where mapper
converts between the view model and models. AutoMapper is a great choice for this task.
Upvotes: 1