c# - rendersection 的这段代码是什么意思?

标签 c# asp.net asp.net-mvc asp.net-mvc-3

我是 Asp.Net MVC3 的初学者。谁能解释一下这段代码的含义:

@section head
{
    @RenderSection("head", false)
}

关于 ScottGu 的文章:

http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

有一个 RenderSection 的例子,但它定义了@section,然后在某处使用了@RenderSection。在这种情况下,section head 被定义,并且在其内部呈现相同的头部,这让我感到困惑。

RenderSection 的作用是什么?我如何找到这里正在渲染的内容?

最佳答案

Scott 曾经写过

The first parameter to the “RenderSection()” helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional, and allows us to define whether the section we are rendering is required or not. If a section is “required”, then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (which can make it easier to track down content errors).

因此,RenderSection 所做的是渲染在模板/ View 中定义的部分(而不是一般的 _Layout)。 在“在我们的 View 模板中实现“侧边栏”部分”下,他解释了如何实现一个部分。

总而言之,您所拥有的是一个名为“head”的部分,它在更深层次/嵌套的 View 中呈现一个名为“head”的部分。

编辑:看看http://blogs.msdn.com/b/marcinon/archive/2010/12/15/razor-nested-layouts-and-redefined-sections.aspx看看我对嵌套 View 的意思 - 但请注意,这篇文章现在已有一年多了。

主布局:

@RenderSection("head", false)

子布局:

@{
    Layout = "~/Views/_MasterLayout.cshtml";
}
@section head
{
    @RenderSection("head")
}

内容:

@{
    Layout = "~/Views/_SubLayout.cshtml";
}
@section head
{
    <title>Content-Layout</title>
}

关于c# - rendersection 的这段代码是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10764930/

相关文章:

c# - 为什么 C# 实例构造函数的名称与返回的类型不同?

asp.net - 请求查询字符串有 np PayPal 返回变量

c# - 与本地 BizTalk 服务器的混合连接

c# - 将匿名类型传递给 MVC ViewData.Model 是否安全?

asp.net - 从 C# 代码发送邮件时出现电子邮件错误

javascript - 在 div 标签中显示响应

c# - C# 中的泛型列表和静态变量行为

javascript - 单击按钮时防止默认值不随机工作

c# - 获取网站 SSL 证书的公钥

asp.net - 在 asp.net 中发送带有图像的电子邮件