开发者

Asp.net MVC retrieving a model object from a ViewModel

开发者 https://www.devze.com 2023-01-12 12:52 出处:网络
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.

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 cr开发者_开发技巧eating a lot of unecessary work for myself by using ViewModels in this way.


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); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消