开发者

MVC3 viewmodel and domain model question

Say I have a domain level "Person" class that contains a lot of properties(FirstName, LastName, Age, Ad开发者_开发百科dress, Telephone, EmailAddress, etc). For the purposes of a view, I only need to pass the Age property. The smaller, the better as the collection is being passed to the client as a JSON string.

What is the best way of managing this?

1) Do I create an anonymous type collection and pass that to the view?

2) Do I create a new "ViewModelPerson" type that only contains the "Age" property.

3) Do I create a new domain "Person" super type and have my Person and ViewModelPerson derive from it (seems a convoluted way of doing things).

Then, whats the best way of persisting these details onto my server (ie passing the age value into a collection of Domain Person objects?

EDIT:

Apologies, I should have said that I'd be returning a collection of Person objects (each with just an Age property).


1) I do not think that is possible, please elaborate

2) Yes! I would call it PersonAgeViewModel though.

3) Very convoluted indeed unless you know that you will derive from Person a lot and are planning to implement TPH or TBT in the database anyway.


If you're interested in only sending the Age (a single age) then don't specify a Model in the view at all. Add the value of the age to the ViewBag.

Check out Hajan's Blog Entry.


Call me pedantic, but I would lean towards creating a ViewModel with a single age property. I'm not sure the ViewBag approach would work unless you're building the JSON in a view. Typically when we return JSON we just use

return Json(model);

I would definitely recommend against a common base type between domain and view models.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜