gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : What is the purpose of @section?

转载 作者:行者123 更新时间:2023-12-03 04:31:09 24 4
gpt4 key购买 nike

对于 ASP.NET MVC 应用程序,我看到 this blog article 。作者 ScottGu 添加 @section到 Index.cshtml。

我有几个问题(引用上面的文章):

  • Index.cshtml 是共享 View 吗?
  • 示例代码使用 @section特定 View 中的代码。为什么?

有人可以解释一下我为什么以及何时使用 @section在 View 中?

最佳答案

@section 用于定义从共享 View 覆盖的内容。基本上,它是您调整共享 View 的一种方法(类似于 Web 表单中的母版页)。

您可能会发现 Scott Gu's write up on this very interesting .

编辑:基于其他问题澄清

@RenderSection 语法进入共享 View ,例如:

<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>

然后,这将使用 @Section 语法放置在您的 View 中:

@section Sidebar{
<!-- Content Here -->
}

在 MVC3+ 中,您可以直接定义用于 View 的布局文件,也可以为所有 View 使用默认 View 。

可以在 _ViewStart.cshtml 中设置通用 View 设置,它定义与此类似的默认布局 View :

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

您还可以设置共享 View 直接在文件中使用,例如直接在index.cshtml中使用,如此片段所示。

@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}

您可以通过多种方式调整此设置,this SO answer 中提到了更多方法。 .

关于asp.net-mvc - ASP.NET MVC : What is the purpose of @section?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com