我的问题是我不能使用@RenderSection从嵌套模板当@RenderSection在基本模板中定义。目前,我有一个嵌套基本模板,它链接到一个子模板,然后在视图页面中使用。当我在基本模板中定义@RenderSection并在视图页面中渲染它时会抛出一个错误。
这是确切的问题。
我想创建一个RenderSection允许我插入自定义脚本。
我的基本模板….
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> @RenderSection("HeaderContent",false) // The region of the header scripts (custom css) </head> <body> @RenderBody() </body> </html>
然后我跳过子模板,因为我不想把任何自定义头部代码在那里,并应用到页面本身。
@section HeaderContent { <script>alert("hi");</script> }
我的问题是,我似乎不能添加自定义头部代码到基本模板从我的正常页面。
以下部分已定义,但尚未呈现布局页〜/ Views / Shared / OneColLayer.cshtml“:”HeaderContent。
@{ Layout = "~/Views/Shared/BaseTemplate.cshtml"; }
我的新基本模板
<head> <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/layout.css")" /> <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/global.css")" /> <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script> <script type="text/javascript" src="@Url.Content("~/js/fadeInFadeOut.js")"></script> <title>@ViewBag.Title</title> @RenderSection("HeaderContent",false) </head> <body> @RenderBody() </body>
我的新子模板
@{ Layout = "~/Views/Shared/BaseTemplate.cshtml"; } @RenderSection("HeaderContent",false) @RenderBody()
我的看法
@{ ViewBag.Title = "Home"; Layout = "~/Views/Shared/OneColLayer.cshtml"; } @section HeaderContent { <h1>Left Content</h1> } <div>my view content</div>
内容被放置在oneCol模板现在的基本模板中。
结果…
<div id="Content"> <h1>Left Content</h1> </div>
解决方法
您需要指定允许在中间模板中传递的部分。
BaseTemplate.cshtml
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> @RenderSection("HeaderContent",false) @* The region of the header scripts (custom css) *@ </head> <body> @RenderBody() </body> </html>
编辑
您的新子模板
@{ Layout = "~/Views/Shared/BaseTemplate.cshtml"; } @section HeaderContent { @RenderSection("HeaderContent",false) } @RenderBody()
如果将render部分放在基本模板的某个部分内部,它将在基本模板上将该部分呈现在正确的位置。
View.cshtml – >使用MiddleLayout.cshtml作为它的布局
@section HeaderContent { <!-- header content that will Now render --> } <!-- page content -->
原文地址:https://www.jb51.cc/aspnet/254476.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。