views:

53

answers:

2

I have a ViewPage, Index.aspx. In it, I have:

<%= Html.Partial("~/Index/ViewUserControl/Promo.ascx, new PromoViewModel()); %>

Now, the constructor for PromoViewModel requires a MemcachedCache object that the index's controller also uses.

How should I pass this MemcachedCache into my partial view?

Should I put the MemcachedCache instance in the ViewData and do this?

<%= Html.Partial("~/Index/ViewUserControl/Promo.ascx,
    new PromoViewModel(ViewData["cache"] as MemcachedCache)); %>

Index.aspx isn't a strongly-typed view; it doesn't use a view model. But should I strongly-type it with a view model that has a public Cache member, then access it through the Model?

<%= Html.Partial("~/Index/ViewUserControl/Promo.ascx, 
    new PromoViewModel(Model.Cache); %>

Now I find out with MVC3, there's a third option: I can set a ViewModel member in the index controller with the Cache member, and use it like this:

<%= Html.Partial("~/Index/ViewUserControl/Promo.ascx, 
    new PromoViewModel(ViewModel.Cache); %>

Which is more appropriate? This seems a little confusing/silly to me.

+2  A: 

Personally, I have it as part of my model that is associated with the view. And load that property in the controller... So I guess I'm saying more along the lines of #2 above. Except that my View's Model would contain the "PromoViewModel" instance:

public class MainViewModel {
    public string Prop1{get; set;}

    public PromoViewModel Promo {get; set; }
}

public class MainController {
    public ActionResult Hello() {
        // Retrieve "cache" or whatever
        var promoModel = new PromoViewModel(cache);

        return new MainViewModel {Prop1 = "Hello", Promo = promoModel };
    }
}

My rationale is that my view's model is just that, its all the stuff I need to display on my page. My controller is responsible for assembling it, various services doing most of the work, etc...

Bryce Fischer
I like this. This is the direction I was planning on going in if I can get my coworkers onboard. Thank you for the backup support. :)
SnickersAreMyFave
+1 for the rationale; I prefer option two for that reason myself.
Andrew Barber
+1 that's the way I do it. I want to add that depending on the scenario, you can do extra lifting in an action filter.
eglasius
Here's a link I just came across that describes it pretty much: http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
Bryce Fischer
A: 

I would prefer your second option for MVC2, and the third if you know you will be using MVC3 when the app goes live (and are confident that feature will remain).

The options you listed represent a progression of features in the MVC versions, basically.

Andrew Barber