Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在mvc中访问_layout.cshtml中的单个视图?_C#_Asp.net Mvc_Layout - Fatal编程技术网

C# 如何在mvc中访问_layout.cshtml中的单个视图?

C# 如何在mvc中访问_layout.cshtml中的单个视图?,c#,asp.net-mvc,layout,C#,Asp.net Mvc,Layout,在MVC中,如何访问_layout.cshtml中的单个视图 public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult ContactUs() { return View();

在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>
}
@{
ViewBag.Title=“ContactUs”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
联系方式
@联络处{
这是联系人视图
}
Header.cshtml

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

<h2>Header</h2>

@section Header{
    <h1>this is header view</h1>
}
@{
ViewBag.Title=“Header”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
标题
@节头{
这是标题视图
}
_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(“Header”)//附加信息:未定义节:“Header”。
@RenderBody()
@RenderSection(“ContactUs”)//附加信息:未定义节:“ContactUs”。
2016@CopyRightsReserved

@渲染部分(“”)
//附加信息:未定义章节:“标题”。在运行时获取错误


我做错了什么???

您对渲染的使用是错误的。RenderSection用于呈现视图中定义的HTML代码段的部分。无法使用RenderSection调用控制器操作


或者,您可以使用Html.RenderAction来呈现控制器操作。但是,您需要返回操作的PartialView结果

只需更新您的_Layout.cshtml即可将其他参数传递给RenderSection:

@RenderSection("Header", false)
这样,当页面没有指定节时,它不会引发异常


顺便说一句,看起来您可能希望渲染局部视图。在这种情况下,需要将标题视图更新为smth simple:

<h2>Header</h2>

当我在index.cshtml中声明头函数时,然后渲染部分工作,但当我通过控制器创建单个视图时,则渲染部分不工作??是的,这是正确的渲染部分的范围仅渲染视图文件中定义的部分。您可以使用Html.RenderAction或简单的Html.Partial来呈现标题
@Html.Action和@{Html.RenderAction(“”;}
这两个函数都只适用于部分视图,我错了与否??从代码中可以看出,您真正需要的只是部分视图。
@Html.Partial("Header")