[英]What's the best way of structuring hiearchy of views in ASP.NET MVC?
I'm currently converting a ASP.NET webforms solution to MVC. 我目前正在将ASP.NET Web表单解决方案转换为MVC。
In webforms we besides the site.master we have master pages where we keep the common code and head imports for each section. 在webforms中,除了site.master之外,我们还有母版页,在这些母版页中,我们保留通用的代码并导入每个部分的标题。 So a normal page inheritance goes like so:
因此,正常的页面继承是这样的:
Site.master -> section.Master -> page.aspx
In MVC I'm unclear as to where to place the code common to a section. 在MVC中,我不清楚某个部分共有的代码放置在何处。 Is splitting the section content into partial views the only solution?
将节内容拆分为局部视图是唯一的解决方案吗? So it becomes?
变成这样了吗?
Layout.cshtml -> page.cshtml -> any-number-of-partial-views
To give an example, if I need a single CSS file to be shared across all 10 section pages, I can put it in a partial view and render it on each page but doesn't feel incredibly efficient. 举个例子,如果我需要在所有10个部分的页面上共享一个CSS文件,则可以将其放在局部视图中并在每个页面上呈现它,但是效率并不令人难以置信。 Or maybe I just need to get my head around to this new way of working.
或者,也许我只需要开始研究这种新的工作方式。
You can use sections in MVC as well. 您也可以在MVC中使用部分 。
In your _Layout.cshtml
you might have something like this: 在
_Layout.cshtml
您可能会_Layout.cshtml
以下情况:
@RenderSection("testSection",required:false)
And in your child view you can specify what HTML should be rendered in this section or you can leave it all together because required
has been set to false: 在子视图中,您可以指定在本节中应呈现的HTML,也可以将所有HTML放在一起,因为
required
设置为false:
@section testSection{
<h1>Test</h1>
}
Partial view is your big friend if you would like to reuse the code several places. 如果您想在多个地方重复使用代码,则部分视图是您的大朋友。
You can put partial view inside Views > ControllerNameAsFolderName > view pages (put here) to use only in same controller views or even inside Shared folder to use globally. 您可以将部分视图放入“视图”>“ ControllerNameAsFolderName”>“视图页面”(放在此处),以仅在相同的控制器视图中使用,甚至可以在“共享”文件夹中使用以全局使用。
section
is another option, this is like UserControl
(in web forms). section
是另一个选项,类似于UserControl
(在Web表单中)。 create section reference @RenderSection("sectionName", required:false)
on Layout page and use it on view pages like 在“布局”页面上创建部分引用
@RenderSection("sectionName", required:false)
并在诸如以下的视图页面上使用
@section sectionName{
<div>content goes here</div>
}
Assume you want to put something (like meta infos) inside <head>
from view pages, in this case you can create a section
in _Layout.cshtml
page and then use that section
on view pages. 假设您想在视图页面的
<head>
放入一些内容(例如元信息),在这种情况下,您可以在_Layout.cshtml
页面中创建一个section
,然后在视图页面上使用该section
。
This way you can place your code at certain location in DOM structure from any page. 这样,您可以从任何页面将代码放置在DOM结构中的特定位置。
section
has a great feature that allow you to mark it as required:false/true
. section
具有一项出色的功能,可让您将其标记为required:false/true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.