Reputation: 5143
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.
Upvotes: 0
Views: 2341
Reputation: 40150
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.
Upvotes: 0
Reputation: 5442
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...
Upvotes: 2