views:

20

answers:

1

So I am using ViewModels to pass data from/to the web forms in my MVC application, as seems to be recommended practice from what I have read.

My question is what is the normal approach to then map the ViewModel into an actual domain entity?

I'm guessing I should probably add a 'GetObject' method to my ViewModels so I have something like:

[AcceptVerbs(HttpVerbs.Post)]
public void CreatePerson(PersonViewModel model)
{
    Person p = model.GetPerson();
    _repository.Save(p);
} 

Is this the right approach? It seems like I'm creating a lot of unecessary work for myself by using ViewModels in this way.

A: 

Assuming that you're binding your controls to properties of the Person object in the View like so

<% Html.TextBoxFor(model => model.Person.Name) %>

You can have the following method to accept only the person model

[AcceptVerbs(HttpVerbs.Post)] 
public void CreatePerson([Bind(Prefix="Person")]Person person) 
{ 
    _repository.Save(person); 
}
Jaimal Chohan
I'm not sure I understand, or I think you might be missing the point. I don't expose the underlying Person object in anyway to the front end. All data is passed to/from front end as formatted string data in a ViewModel (which is created from the Person entity).
fearofawhackplanet
Ahh yea, you're might be taking the abstraction between View and Model a little too far. i prefer the approach of wrapping Models in ViewModels and binding them to the View. It also allows me to have DataAnnotations applied on the Model validated in the View.
Jaimal Chohan