在MVC中,如何在_layout.cshtml中访问单个视图?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ContactUs()
{
return View();
}
public ActionResult Header()
{
return View();
}
}
当我写信时单击添加视图(标题和联系人(,然后选择此视图,如下所示。 ContactUs.cshtml
@{
ViewBag.Title = "ContactUs";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ContactUs</h2>
@section ContactUs{
<h1>this is contact view</h1>
}
Header.cshtml
@{
ViewBag.Title = "Header";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Header</h2>
@section Header{
<h1>this is header view</h1>
}
_Layout.cshtml
<body>
<div class="container body-content">
@RenderSection("Header") //Additional information: Section not defined: "Header".
@RenderBody()
@RenderSection("ContactUs") //Additional information: Section not defined: "ContactUs".
<footer>
<p>2016@CopyRightsReserved</p>
</footer>
</div>
@RenderSection("")
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
附加信息:未定义的部分:"标头"。 获取错误运行时
我做错了什么??
你对RenderSection的使用是错误的。呈现部分用于呈现视图中定义的 HTML 代码段部分。不能使用 RenderSection 调用控制器操作。请在此处阅读。
或者,您可以使用 Html.RenderAction 来呈现控制器操作。但是,您需要从操作中返回部分视图结果。 阅读此处。
只需更新_Layout.cshtml即可将其他参数传递给RenderSection:
@RenderSection("Header", false)
这样,当页面未指定部分时,它就不会引发异常。
顺便说一句,看起来您可能正在寻找渲染部分视图。在这种情况下,您的标题视图需要更新为简单:
<h2>Header</h2>
在 _Layout.cshtml 中,您只需要调用
@Html.Partial("Header")