【问题标题】:How to access a individual view in _layout.cshtml in mvc?如何在 mvc 中访问 _layout.cshtml 中的单个视图?
【发布时间】:2020-04-15 06:36:38
【问题描述】:

在 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>

//附加信息:未定义部分:“标题”。获取错误运行时

我做错了什么??

【问题讨论】:

    标签: c# asp.net-mvc layout


    【解决方案1】:

    您对 RenderSection 的使用是错误的。 RenderSection 用于渲染视图中定义的 HTML sn-p 部分。您不能使用 RenderSection 来调用控制器操作。 Read here.

    您也可以使用 Html.RenderAction 来呈现控制器动作。但是,您需要从操作中返回 PartialView 结果。 Read Here.

    【讨论】:

    • 当我在 index.cshtml 中声明头函数时,渲染部分工作,但是当我通过控制器创建单个视图时,渲染部分不起作用??
    • 是的,这是正确的 RenderSection 的范围只是渲染视图文件中定义的部分。您可以使用 Html.RenderAction 或简单地使用 Html.Partial 来呈现您的标题
    • @Html.Action and @{Html.RenderAction("");} 这两个函数都只适用于部分视图我错了吗??
    • 我从您的代码中看到,您真正需要的只是部分视图。
    【解决方案2】:

    只需更新您的 _Layout.cshtml 以将附加参数传递给 RenderSection:

    @RenderSection("Header", false)
    

    这样,当页面没有指定部分时,它不会抛出异常。


    顺便说一句,看起来您可能正在寻找渲染局部视图。在这种情况下,您的 Header 视图需要更新为非常简单:

    <h2>Header</h2>
    

    在 _Layout.cshtml 中你只需要调用

    @Html.Partial("Header")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多