views:

236

answers:

3

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?

+2  A: 

Hello,

You can do:

new ViewDataDictionary(new { ForPrinting = True })

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

Brian
I've tried that, but on the other end ViewData.Count == 0.
J. Pablo Fernández
That is read as model, not as the view data.
J. Pablo Fernández
You are right, my apologies. I was thinking the RouteValuesDictionary, though oddly named for this function, you can use this as new RouteValuesDictionary(new { .. }), and this extracts the property values and make them individual key/value pairs, which then you can pass these to the viewdatadictionary instance.
Brian
Yes, with RouteValuesDictionary you can do it.
J. Pablo Fernández
A: 

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 }) %>
J. Pablo Fernández