MVC视图模型获取子对象

时间:2010-10-27 16:35:26

标签: asp.net-mvc model view

我有一个主要的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));  
            }   
            }       

1 个答案:

答案 0 :(得分:1)

拥有视图模型会更容易(您可以忘记FormCollectionTryUpdateModel):

[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是完成此任务的绝佳选择。