ASP.NET MVC:@section 的目的是什么? [英] ASP.NET MVC: What is the purpose of @section?

查看:33
本文介绍了ASP.NET MVC:@section 的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 ASP.NET MVC 应用程序,我看到 这篇博客文章.作者 ScottGu 在 Index.cshtml 中添加了 @section.

我有几个问题(参考上面的文章):

  • Index.cshtml 是共享视图吗?
  • 示例代码在特定视图中使用了 @section 代码.为什么?

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

解决方案

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

您可能会发现 Scott Gu 写了一篇非常有趣的文章.

基于额外的问题说明

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

这将使用 @Section 语法放置在您的视图中:

@section 侧边栏{<!-- 内容在这里-->}

在 MVC3+ 中,您可以直接定义要用于视图的布局文件,也可以为所有视图设置默认视图.

可以在 _ViewStart.cshtml 中设置常见的视图设置,它定义了与此类似的默认布局视图:

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

您也可以将共享视图设置为直接在文件中使用,例如 index.cshtml 直接如本代码段所示.

@{ViewBag.Title = "企业主页";ViewBag.BodyID = "主页首页";布局 = "~/Views/Shared/_Layout2.cshtml";}

您可以通过多种方式调整此设置,这个答案.

For an ASP.NET MVC application, I saw this blog article. The author ScottGu adds @section to the Index.cshtml.

I have a couple of questions (referring to the article above):

  • Is Index.cshtml a shared View?
  • The example code uses @section code in a particular view. Why?

Can someone please explain why and when I would use @section in a View?

解决方案

@section is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).

You might find Scott Gu's write up on this very interesting.

Edit: Based on additional question clarification

The @RenderSection syntax goes into the Shared View, such as:

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

This would then be placed in your view with @Section syntax:

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

In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.

Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:

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

You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.

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

There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.

这篇关于ASP.NET MVC:@section 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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