Pass ViewData to RenderPartial

Viewed 24680

I'm trying to call this method:

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

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

but I don't see any way to construct a ViewDataDictionary in an expression, like:

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

Any ideas how to do that?

4 Answers

I've managed to do this with the following extension method:

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);
}

calling it this way:

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

You can do:

new ViewDataDictionary(new { ForPrinting = True })

As viewdatadictionary can take an object to reflect against in its constructor.

Related