使用 _viewstart.cshtml 和部分 Razor 视图的正确方法? [英] Correct way to use _viewstart.cshtml and partial Razor views?

查看:20
本文介绍了使用 _viewstart.cshtml 和部分 Razor 视图的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 _viewstart.cshtml 自动为我的视图分配相同的 Razor 布局.

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

这是我的 Views 文件夹根目录下的一个简单的文件,如下所示:

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

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

这比将@Layout 指令添加到每个视图中更加枯燥.

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

然而,这给 Razor 部分 视图带来了问题,因为它们运行 _viewstart.cshtml 的内容,因此错误地为自己分配了一个布局,这使得它们,嗯,不再是部分的.

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.

这是一个假设的项目,显示了 _viewstart.cshtml 文件、共享的 _layout.shtml 文件和局部视图(AnonBar.cshtml").

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

目前,我解决这个问题的方法是在每个局部视图中添加以下行:

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

@{
    Layout = "";
}

这似乎是在 Razor 中将视图表示为部分视图的错误方式.(请注意,与 Web 表单视图引擎不同,部分视图的文件扩展名是相同的.)

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:

  • 将所有局部视图放入一个公共文件夹中,这样它们就可以共享一个公共 _viewstart.cshtml.这打破了视图与其控制器位于同一文件夹中的惯例.
  • 不使用局部视图.

这是 Razor 视图引擎团队仍在充实的东西,还是我遗漏了一个基本概念?

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

推荐答案

如果你从控制器中return PartialView()(而不是return View()),那么_viewstart.cshtml 不会被执行.

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

这篇关于使用 _viewstart.cshtml 和部分 Razor 视图的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆