Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.RenderPartial call from masterpage

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.

like image 327
Dragan Panjkov Avatar asked Sep 07 '08 21:09

Dragan Panjkov


1 Answers

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

like image 117
user113588 Avatar answered Nov 09 '22 19:11

user113588