如何插入“File1.cshtml”进入主视图部分(How to insert “File1.csh

2019-10-20 15:38发布

好吧,即时通讯可能这样做不对......但在我的主要_layout我有这样的:

<div id="navigation">
            @RenderSection("Navigation")
        </div>

它指向这在我Index.cshtml观点:

@section Navigation{
  <-- Need this to point to Views/Shared/Navigation.cshtml -->
}

但我不希望有与我的所有代码一个巨大的文件,所以我需要知道如何指向一个名为“Navigation.cshtml”这一节里面的文件 - 基本上让我有我的所有部分在单独的,独立的文件。

我试着只是做@RenderPage(“Navigation.cshtml”)在_layout而不是@RenderSection,并给出错误。

- 编辑 -

如果我添加此代替@RenderSection()

<div id="navigation">
          = @RenderPage("~Views/Shared/Navigation.cshtml")
        </div>

我得到这个:

The file "~/Views/Shared/~Views/Shared/Navigation.cshtml" could not be rendered, because it does not exist or is not a valid page.

- 编辑 -

FULL _Layout.cshtml:

   <!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript">    </script>
</head>

<body>
<div id="wrapper">

    <div id="content">
        <!-- BANNER -->
        <div id="banner">

        </div>
        <!-- NAVIGATION -->
        <div id="navigation">
         @RenderPage("Navigation.cshtml")
        </div>
        <!-- MAIN DISPLAY -->
        <div id="main">
            @RenderBody()
        </div>
        <!-- FOOTER -->
        <div id="footer">

        </div>
    </div>
</div>

Answer 1:

与全视路试,也可以使用Html.Partial()@Html.RenderPartial()

<div id="navigation">
                @RenderPage("Navigation.cshtml")
</div>

Html.Partial():

<div id="navigation">
            @Html.Partial("~/Views/Shared/Navigation.cshtml")
</div>

Html.RenderPartial():

<div id="navigation">
            @{ Html.RenderPartial("~/Views/Shared/Navigation.cshtml"); }
</div>


Answer 2:

如果你想保持@RenderSection("Navigation")在您的_Layout你可以试试下面的代码在您的视图。

@section Navigation{
    @Html.Partial("~/Views/Shared/Navigation.cshtml")
}

或者你可以改变_Layout如下。

<div id="navigation">
    @Html.Partial("~/Views/Shared/Navigation.cshtml")
</div>


Answer 3:

尝试只是为了渲染页面“视图/共享/ Navigation.cshtml”作为这样的局部视图:

<div id="navigation">
    @Html.RenderPartial("Navigation")
</div>


文章来源: How to insert “File1.cshtml” into a section in main view