views:

34

answers:

1

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));  
            }   
            }       
+1  A: 

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.

Darin Dimitrov
I tried this like this Contact contact = Mapper.Map<Contact, Contact>(contactView.Contact); repository.Save(); This updates values of Contact object but when I call save its not being saved to the database.I am using LINQ with EF.
Mathew
Your `Save` function on the repository should take the instance to save.
Darin Dimitrov
Sorry but as I am very new to EF as well as LINQ I only see these 3 methods http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.savechanges.aspx. How can I update this cause I will have existing contact in database.
Mathew
Mathew
Not sure but after many tries with Automapper tried as this and worked fine ! Contact contact = repository.GetContactById(contactView.Contact.Id); if (TryUpdateModel(contact, "Contact")) { repository.Save(); }
Mathew