Html.RenderPartial call from masterpage

12,083

Solution 1

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

Solution 2

I had a similar post and came up with an object model to handle it.

I HATE the non-strongly typed views so went with this approach and it is working well.

Solution 3

I think that your solution may lie in the land of MVC 2.0 RC and beyond...

Phil Haack posted an article on his blog: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

Share:
12,083
Dragan Panjkov
Author by

Dragan Panjkov

Senior Customer Engineer at MicrosoftOne of first 500 StackOverflow Users#SOReadyToHelphttp://www.dragan-panjkov.com@panjkov

Updated on June 07, 2022

Comments

  • Dragan Panjkov
    Dragan Panjkov almost 2 years

    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.