Reputation: 4484
I have a master page that uses @RenderBody to display the current controller\action content. I'm running into a situation where I'd like to show a partial view depending on which controller is being rendered with the @RenderBody. Is this possible using @RenderAction or @RenderPartial? Thanks
Upvotes: 4
Views: 5449
Reputation: 82357
Go to your shared views, and inside of _Layout.cshtml place @Html.Partial("_displayCustomPartial")
. Then, go back to your shared views folder, and create a new view _displayCustomPartial
. Open _displayCustomPartial.cshtml
and then inside of it use this code:
@{
var controllerCalled = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue;
var actionCalled = ViewContext.Controller.ValueProvider.GetValue("action").RawValue;
switch(controllerCalled){
case "Home":
@Html.Partial("_homePartial");
break;
case "Work":
@Html.Partial("_workPartial");
break;
case default:break;
}
}
This scenario assumes you have premade views ready for each controller scenario (I included action code as well in case you wanted to use that). If no premade views are ready, then just put in the code that should show up for each case instead of rendering another view.
A main difference between this and Sections is that Sections share a model with their view, and using partial views would allow the inclusion of a separate model.
Upvotes: 2
Reputation: 3181
You may want to take a look at Sections (RenderSection) feature. Well described by Scott Gu http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
Upvotes: 3