开发者

what is the correct way of using Models with Partial Views in ASP.NET MVC2?

I'm pretty new to MVC, but now feel pretty comfortable with the pattern, particularly finding ViewModels to be an excellent bridge between controller and view.

However, I'm now going to have to use Partial Views, and am a little confused.

Requirement

Ok, in the Wire Frames we have many different pages, but which share a common "grid".

The Grid will be a Partial View and will always render/consume/manipulate the same TYPE of data.

Questions

So, the main Views that include the partial view will have different Models... so how do I handle the models from within the partial view.

Should all Models for Views that use that certain Partial View have a nested model for the partial view as a property?

What the best practice here?

co开发者_运维百科ol, cheers


I find that when I am putting together a Partial, it helps immensely if I consider what the Model for that Partial will be. I almost always find that if I take a moment to consider that, the reusability of the partial increases a lot.

A Partial should usually use some natural sub-set or variation of the data in the Model of the whole View. When your creation of a Partial starts with that in mind, having to think too much about "what model should my partial use" is often an indication that perhaps you should be creating a different partial instead of trying to re-use one.

If you are having to re-construct a new model for a Partial, I think the problem may be that your whole View's model isn't covering everything you need.

With that said, though; there are many times where I have a Partial that uses a Model that seems to be separate from the whole View's Model. But most of the time those models are new/empty objects - not ones that need to be instantiated and have properties set, etc. (this usually happens for Partials that are being used in Ajax-related updates)

Note that MVC2 has something for this too, though; Html.RenderAction() lets you call a whole new Action (which would have its own Model) and render it within the current View. I try to avoid needing to use it, myself, actually... but it would feel better, to me, than trying to 'build' some new Model for a Partial, or adding in unnatural information in the current ViewModel.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜