将ViewData传递给RenderPartial

19

我试图调用这个方法:

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

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

但是我没有看到任何一种方法可以在表达式中构造一个ViewDataDictionary,例如:

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

有什么想法如何去做到这一点吗?

4个回答

29

这对我起作用了:

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

11

我已经使用下面的扩展方法实现了这个:

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 的重载,你就必须创建更多自己的方法重载。这很聪明,但我觉得你可能会为自己设置更多的工作量,而不是减少。 - AaronLS

3

您可以做以下操作:

new ViewDataDictionary(new { ForPrinting = True })

视图数据字典(viewdatadictionary)可以在其构造函数中接受一个对象以进行反射。


你是对的,我道歉。我在想RouteValuesDictionary,虽然这个函数的命名有些奇怪,但你可以使用它作为new RouteValuesDictionary(new { .. }),然后提取属性值并将它们变成单独的键/值对,然后将它们传递给ViewDataDictionary实例。 - Brian Mains
是的,使用RouteValuesDictionary你可以做到。 - pupeno

0

这不完全是你所要求的,但你可以使用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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接