Calling @Html.Partial to display a partial view belonging to a different controller

C#asp.netasp.net MvcRazor

C# Problem Overview


I am developing an ASP.NET MVC 3 application, whose content pages have a common pattern of layout elements. However, because the login page does not follow this layout, I cannot place this layout in \Views\Shared\_Layout.cshtml.

So I would like to add another shared layout, say, \Views\Shared\_Content.cshtml, and call it from the content views... but unfortunately those views belong to different controllers.

Is there any way to invoke @Html.Partial for a view belonging to a different controller?

C# Solutions


Solution 1 - C#

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Solution 2 - C#

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpyonView Question on Stackoverflow
Solution 1 - C#GvSView Answer on Stackoverflow
Solution 2 - C#CraigView Answer on Stackoverflow