159

I'm using _viewstart.cshtml to automagically assign the same Razor Layout to my views.

It's a dead simple file in the root of my Views folder that looks like this:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This is more DRY than adding the @Layout directive to every single view.

However, this poses a problem for Razor partial views, because they run the contents of _viewstart.cshtml and therefore incorrectly assign themselves a layout, which makes them, um, no longer partial.

Here's a hypothetical project, showing the _viewstart.cshtml file, the shared _layout.shtml file, and a partial view ("AnonBar.cshtml").

Example project structure

Currently, the way that I'm getting around this is by adding the following line to every partial view:

@{
    Layout = "";
}

This seems like the wrong way to denote a view as a partial in Razor. (Note that unlike the web forms view engine, the file extension is the same for partial views.)

Other options I considered but that are even worse:

  • Putting all partial views into a common folder, so they could share a common _viewstart.cshtml. This breaks the convention of views being in the same folder as their controller.
  • Not using partial views.

Is this something that is still being fleshed out by the Razor view engine team, or am I missing a fundamental concept?

Community
  • 1
  • 1
Portman
  • 31,785
  • 25
  • 82
  • 101

1 Answers1

240

If you return PartialView() from your controllers (instead of return View()), then _viewstart.cshtml will not be executed.

marcind
  • 52,944
  • 13
  • 125
  • 111
  • 7
    Aha, did not know about the `PartialViewResult` class. That was what I needed. – Portman Nov 02 '10 at 22:31
  • 6
    As a follow-up, I've found that I need to **also** explicitly set the return type of the action method to `PartialViewResult` instead of the usual `ActionResult`. – Portman Nov 03 '10 at 21:55
  • 2
    @Portman are you seeing issues when the action method's return type is not `ActionResult`? I'm surprised that this is an issue because the MVC runtime should not behave any differently in this case (i.e. as long as the type returned by the action method is `ActionResult` or any class derived from it things should just work). – marcind Nov 03 '10 at 22:37
  • @marcind I get a Stack Overflow on w3wp.exe if I set the return type to `ActionResult`. Works fine if the return type is `PartialViewResult`. Think I need to file a Connect bug? – Portman Nov 03 '10 at 23:50
  • Does sound like one to me - do shout back if you submit a Connect bug, will vote it up. – Dav Nov 28 '10 at 21:49