asp.net-mvc 如何在 MVC3 的局部视图中渲染一个部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13764936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:27:28  来源:igfitidea点击:

How to render a Section in a Partial View in MVC3?

asp.net-mvcasp.net-mvc-3razorasp.net-mvc-partialviewasp.net-mvc-views

提问by Max

In a MVC3 project, I have a "_Layout.vbhtml" file with this code

在 MVC3 项目中,我有一个带有此代码的“_Layout.vbhtml”文件

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    ...
    <script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>
    @RenderSection("Scripts", false)
  </body>
</html>

Then, I have a Partial View "ValidationScripts.vbhtml" in the Shared folder with

然后,我在共享文件夹中有一个部分视图“ValidationScripts.vbhtml”

@Section Scripts
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.fix.js")"></script>  
    <script src="@Url.Content("~/Scripts/localization/messages_de.js")"></script>      
End Section

If I call the Partial View from a View like this...

如果我从这样的视图中调用局部视图......

@ModelType MvcExample.MyModel
@Code
    ViewData("Title") = "Test"
End Code

@Html.Partial("ValidationScripts")

<h2>Just a Test</h2>
...

the Section "Scripts" is not rendered on the page, and the output HTML is

页面上未呈现“脚本”部分,输出 HTML 为

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    ...
    <script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>

  </body>
</html>

How can I render the Section in the Partial View ?

如何在局部视图中渲染该部分?

回答by Erik Philips

I had the same issue on top of duplicate scripts, so I created a couple of Extension methods:

我在重复脚本上遇到了同样的问题,所以我创建了几个扩展方法:

public static class HtmlHelperExtensions
{
  private const string _jSViewDataName = "RenderJavaScript";
  private const string _styleViewDataName = "RenderStyle";

  public static void AddJavaScript(this HtmlHelper htmlHelper, 
                                   string scriptURL)
  {
    List<string> scriptList = htmlHelper.ViewContext.HttpContext
      .Items[HtmlHelperExtensions._jSViewDataName] as List<string>;
    if (scriptList != null)
    {
      if (!scriptList.Contains(scriptURL))
      {
        scriptList.Add(scriptURL);
      }
    }
    else
    {
      scriptList = new List<string>();
      scriptList.Add(scriptURL);
      htmlHelper.ViewContext.HttpContext
        .Items.Add(HtmlHelperExtensions._jSViewDataName, scriptList);
    }
  }

  public static MvcHtmlString RenderJavaScripts(this HtmlHelper HtmlHelper)
  {
    StringBuilder result = new StringBuilder();

    List<string> scriptList = HtmlHelper.ViewContext.HttpContext
      .Items[HtmlHelperExtensions._jSViewDataName] as List<string>;
    if (scriptList != null)
    {
      foreach (string script in scriptList)
      {
        result.AppendLine(string.Format(
          "<script type=\"text/javascript\" src=\"{0}\"></script>", 
          script));
      }
    }

    return MvcHtmlString.Create(result.ToString());
  }

  public static void AddStyle(this HtmlHelper htmlHelper, string styleURL)
  {
    List<string> styleList = htmlHelper.ViewContext.HttpContext
      .Items[HtmlHelperExtensions._styleViewDataName] as List<string>;

   if (styleList != null)
   {
     if (!styleList.Contains(styleURL))
     {
       styleList.Add(styleURL);
     }
   }
   else
   {
     styleList = new List<string>();
     styleList.Add(styleURL);
     htmlHelper.ViewContext.HttpContext
       .Items.Add(HtmlHelperExtensions._styleViewDataName, styleList);
   }
 }

 public static MvcHtmlString RenderStyles(this HtmlHelper htmlHelper)
 {
   StringBuilder result = new StringBuilder();

   List<string> styleList = htmlHelper.ViewContext.HttpContext
     .Items[HtmlHelperExtensions._styleViewDataName] as List<string>;

   if (styleList != null)
   {
     foreach (string script in styleList)
     {
       result.AppendLine(string.Format(
         "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />", 
         script));
     }
   }

  return MvcHtmlString.Create(result.ToString());
  }
}

On any View or Partial View or Display/Edit Template you simply add what you need:

在任何视图或部分视图或显示/编辑模板上,您只需添加您需要的内容:

@{
  Html.AddJavaScript("http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js");
}

In your Layouts you render it where you want it:

在您的布局中,您可以将它呈现在您想要的位置:

<!DOCTYPE html>
<html lang="en">
  <head>
  @Html.RenderStyles()
  @Html.RenderJavascripts()

The only issue you may have is the order in which the scripts are rendered if you get to complex. If that becomes an issue, simply add the scripts to the bottom of your views/templates, and simply reverse the order in the extension method before rendering them.

如果您变得复杂,您可能遇到的唯一问题是脚本的呈现顺序。如果这成为一个问题,只需将脚本添加到视图/模板的底部,并在渲染它们之前简单地反转扩展方法中的顺序。

回答by VJAI

You can't use sections in partial views. You can go for custom helpers as mentioned here.

您不能在局部视图中使用截面。您可以按照此处提到的方式使用自定义助手。

回答by Zar Shardan

I think you should be using helpers for this http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

我认为您应该为此使用帮助程序http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

If you can upgrade to MVC4 you could use the new bundling and minification feature: http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification. It is specifically designed to address what you are trying to achieve (including scripts).

如果您可以升级到 MVC4,您可以使用新的捆绑和缩小功能:http: //www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification。它专门用于解决您要实现的目标(包括脚本)。

Alternatively you could use http://combres.codeplex.com/with MVC3

或者,您可以将http://combres.codeplex.com/与 MVC3 一起使用

回答by frictionlesspulley

If I understand correctly you have a structure

如果我理解正确,你有一个结构

  • Layout.cshtml
  • View - X
    • PartialView Y (called inside View-X)
  • 布局.cshtml
  • 查看 - X
    • PartialView Y(在 View-X 中调用)

then you need to define the

那么你需要定义

@section Script{ .... }in the View-Xand NOT PartialView Ysince View-Xhas its View.Layoutset to Layout.cshtml

@section Script{ .... }View-XNOT PartialView Y 中,因为View-XView.Layout设置为Layout.cshtml

回答by MFields

all this was great info, however if you look at his original code, Section is capitalized therefore not being recognized.

所有这些都是很好的信息,但是如果您查看他的原始代码,Section 大写,因此无法识别。

it should be @sectionblahblah not @Section

应该是@sectionblahblah不是@Section