Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
Portman Avatar asked Oct 14 '22 16:10

Portman


People also ask

What is the right way to render partial view?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .

How do you use partial view in razor pages?

A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.

When should partial views be used?

You should use partial views in two primary cases: When you need to reuse a similar "group of components" in multiple locations in a website (e.g. a "login form" might be used in different places in the website).

What is the difference between _ViewImports Cshtml and _ViewStart Cshtml?

Code in the _ViewStart. cshtml file will only be run for non-layout pages. Code in the _ViewImports. cshtml file will be run for both layout and non-layout pages.


1 Answers

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

like image 239
marcind Avatar answered Oct 16 '22 05:10

marcind