将ViewData传递给RenderPartial

pup*_*eno 17 asp.net-mvc renderpartial

我试着调用这个方法:

RenderPartialExtensions.RenderPartial Method (HtmlHelper, String, Object, ViewDataDictionary)
Run Code Online (Sandbox Code Playgroud)

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

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

<% Html.RenderPartial("BlogPost", Post, new { ForPrinting = True }) %>
Run Code Online (Sandbox Code Playgroud)

任何想法如何做到这一点?

Mon*_*nor 25

这对我有用:

<% Html.RenderPartial("BlogPost", Model, new ViewDataDictionary{ {"ForPrinting", "true"} });%>
Run Code Online (Sandbox Code Playgroud)


pup*_*eno 10

我已设法使用以下扩展方法执行此操作:

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);
}
Run Code Online (Sandbox Code Playgroud)

这样称呼它:

<% Html.RenderPartialWithData("BlogPost", Post, new { ForPrinting = True }) %>
Run Code Online (Sandbox Code Playgroud)


Bri*_*ins 3

你可以做:

new ViewDataDictionary(new { ForPrinting = True })
Run Code Online (Sandbox Code Playgroud)

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