Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Correct way to use _viewstart.cshtml and partial Razor views?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...