Html.RenderPartial call from masterpage

Dragan Panjkov picture Dragan Panjkov · Sep 7, 2008 · Viewed 12.1k times · Source

Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial?

[EDIT] Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me.

Answer

user113588 picture user113588 · May 28, 2009

How about creating an HtmlHelper extension method that allows you to call a partial view result on the an action on the controller.

Something like

 public static void RenderPartialAction<TController>(this HtmlHelper helper, Func<TController, PartialViewResult> actionToRender)
    where TController : Controller, new()
{
    var arg = new TController {ControllerContext = helper.ViewContext.Controller.ControllerContext};
    actionToRender(arg).ExecuteResult(arg.ControllerContext);
} 

you could then use this in your master page like

<% Html.RenderPartialAction((HomeController x) => x.RenderPartial()) %>

and in your controller the appropriate method

public PartialViewResult RenderPartial()
{

     return PartialView("~/Path/or/View",_homeService.GetModel())
}

Well that is my 2 cents anyway