【问题标题】:Pass ViewData to RenderPartial将 ViewData 传递给 RenderPartial
【发布时间】:2010-01-22 13:12:06
【问题描述】:

我正在尝试调用此方法:

RenderPartialExtensions.RenderPartial Method (HtmlHelper, String, Object, ViewDataDictionary)

http://msdn.microsoft.com/en-us/library/dd470561.aspx

但我没有看到任何在表达式中构造 ViewDataDictionary 的方法,例如:

<% Html.RenderPartial("BlogPost", Post, new { ForPrinting = True }) %>

有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc renderpartial


    【解决方案1】:

    这对我有用:

    <% Html.RenderPartial("BlogPost", Model, new ViewDataDictionary{ {"ForPrinting", "true"} });%>
    

    【讨论】:

      【解决方案2】:

      我已经设法通过以下扩展方法做到了这一点:

      public static void RenderPartialWithData(this HtmlHelper htmlHelper, string partialViewName, object model, object viewData) {
        var viewDataDictionary = new ViewDataDictionary();
        if (viewData != null) {
          foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(viewData)) {
            object val = prop.GetValue(viewData);
            viewDataDictionary[prop.Name] = val;
          }
        }
        htmlHelper.RenderPartial(partialViewName, model, viewDataDictionary);
      }
      

      这样称呼它:

      <% Html.RenderPartialWithData("BlogPost", Post, new { ForPrinting = True }) %>
      

      【讨论】:

      • +1 用于展示如何创建/修改 ViewDataDictionary,但不喜欢采用强类型方法,而是使用更松散类型的方法来避免声明 ViewDataDictionary。如果您习惯使用 RenderPartialWithData,但随后您需要 RenderPartial 的其他重载,则必须为您自己的方法创建更多重载。这很聪明,但我觉得你可能会为自己做更多而不是更少的工作。
      【解决方案3】:

      你可以这样做:

      new ViewDataDictionary(new { ForPrinting = True })
      

      因为 viewdatadictionary 可以在其构造函数中使用一个对象来反映。

      【讨论】:

      • 你说得对,我很抱歉。我在想 RouteValuesDictionary,虽然这个函数的名字很奇怪,但你可以将它用作 new RouteValuesDictionary(new { .. }),这会提取属性值并使它们成为单独的键/值对,然后你可以将它们传递给viewdatadictionary 实例。
      • 是的,使用 RouteValuesDictionary 你可以做到。
      【解决方案4】:

      这不是您所要求的,但您可以使用 ViewContext.ViewBag。

      // in the view add to the ViewBag:
      ViewBag.SomeProperty = true;
      ...
      Html.RenderPartial("~/Views/Shared/View1.cshtml");
      
      // in partial view View1.cshtml then access the property via ViewContext:
      @{
          bool someProperty = ViewContext.ViewBag.SomeProperty;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-22
        • 2010-12-20
        相关资源
        最近更新 更多