100

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?

GvS
  • 52,015
  • 16
  • 101
  • 139
isekaijin
  • 19,076
  • 18
  • 85
  • 153
  • Can someone please have the courage to downvote my stupid questions? I can't do it myself. – isekaijin Mar 01 '18 at 18:55
  • You should be able to vote to close your own question. https://meta.stackexchange.com/questions/163375/vote-to-close-own-question – Michael Freidgeim Mar 01 '18 at 20:02
  • 2
    @pyon I didn't find it stupid at all. It was the first search result to appear based on my Google search query. It's not stupid, just a duplicate. – SomeShinyObject May 18 '18 at 00:31

2 Answers2

167

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

Mark Larson
  • 499
  • 3
  • 13
GvS
  • 52,015
  • 16
  • 101
  • 139
  • 8
    Why does @Html.Partial("~Views/Controller/View", model) need the .cshtml extension? Otherwise, it says view not found. – ashes999 May 22 '11 at 12:05
  • 2
    Resharper 6.1 flags `@Html.Partial("../Controller/View", model)` as an error, but not `@Html.Partial("~/Views/Controller/View.cshtml", model)`. Both work fine at runtime. – Mark Larson May 09 '12 at 17:15
  • @GVs IF windows is using \ for directory then why you use /. Any reason – Anirudha Gupta Jun 07 '13 at 11:13
  • @F1betaIndia, I use a azerty-keyboard, to get / I press SHIFT-:, for the \ I have to press AltGr-<. The Shift-: is easier because the key is larger. – GvS Jun 07 '13 at 11:20
  • The use of `Html.Action(...)` is ingenious and gets me exactly what I need with the `ChildActionOnlyAttribute` applied to the action. – Jeremy Cook Jun 19 '14 at 20:16
  • @CodeswithHammer I didn't, unfortunately. I just kept the `.cshtml` extension and ran with it. – ashes999 Jul 14 '14 at 15:42
  • If you specify action attributes you must go with `[HttpGet]` – 2Yootz Aug 22 '16 at 05:20
  • @ashes999 See Mark Larson's comment right after yours. – Wolfzoon Jul 19 '17 at 12:29
7

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.

Craig
  • 36,306
  • 34
  • 114
  • 197