【问题标题】:How to insert "File1.cshtml" into a section in main view如何将“File1.cshtml”插入主视图的部分
【发布时间】:2014-08-09 16:29:03
【问题描述】:

好吧,我可能做错了......但在我的主要 _Layout 我有这个:

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

在我的 Index.cshtml 视图中指向这一点:

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

但是我不想有一个包含我所有代码的大文件,所以我需要知道如何在这个部分中指向一个名为“Navigation.cshtml”的文件 - 基本上我有我的所有部分在单独的独立文件中。

我尝试只在 _Layout 中执行 @RenderPage("Navigation.cshtml") 而不是 @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.

--编辑--

完整的_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>

【问题讨论】:

  • 是什么错误,在post中补充一下
  • 只检查你的路径......它错了......
  • 是的,当我重做它以得到错误时,这是​​一个错字。正确的路径我得到这个:当我使用@RenderPage 时得到这个:以下部分已定义但尚未为布局页面“~/Views/Shared/_Layout.cshtml”呈现:“导航”

标签: asp.net-mvc asp.net-mvc-4 razor


【解决方案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>

【讨论】:

  • 我在使用@RenderPage 时得到这个:以下部分已定义但尚未为布局页面“~/Views/Shared/_Layout.cshtml”渲染:“导航”。
  • 你能在你的问题中显示你的_Layout.cshtml代码吗
  • 如果你写:@RenderPage("Navigation.cshtml") 那么你看到了什么错误?
【解决方案2】:

如果您想将@RenderSection("Navigation") 保留在您的_Layout 中,您可以在您的视图中尝试以下代码。

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

或者您可以更改_Layout,如下所示。

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

【讨论】:

    【解决方案3】:

    尝试将页面“Views/Shared/Navigation.cshtml”呈现为像这样的局部视图:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 2014-12-02
      相关资源
      最近更新 更多