views:

41

answers:

2

What is the recommended "cleanest" way to manage a partial that appears on many views and also requires a viewmodel (assume it needs to get some data from a DB).

+3  A: 

In the new ASP.NET MVC 2 framework, you can use the Html.RenderAction() method. This allows you to call an action from the view, and get the generated view inside your view: http://www.davidhayden.me/2009/11/htmlaction-and-htmlrenderaction-in-aspnet-mvc-2.html

The MVCContrib-project has something called Subcontroller, which basically gives you the same functionality: http://jeffreypalermo.com/blog/mvccontrib-latest-release-now-with-subcontroller-support/

Pbirkoff
I like that !!!
Obalix
Using Html.RenderAction(), which controller would you be calling into?
Bobbie
as far as I can see, you're calling into the current controller. To call another controller, you can give an extra param to the RenderAction-method, with the name: Html.RenderAction("ActionName", "ControllerName")
Pbirkoff
Right, but then you would have to designate one controller to be the supplier of all the "common" data. I guess it has to come from somewhere!
Bobbie
A: 

Just put this partial view in the Views/Shared folder and it can be accessed by any other view.

If you use the ViewModel pattern you can compose your ModelView with the object needed by this partial view. Like this:

public class MyPartialViewViewModel
{
    // my properties here    
}

public class MyView1ViewModel
{
    public MyPartialViewViewModel Partial {get; private set;}
    public MyView1ViewModel(MyPartialViewViewModel partial)
    {
       this.Partial = partial;
    }
}

And then you just have to passe the Partial property to your partial view.

VinTem