19

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?

Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

4 Answers4

29

This worked for me:

<% Html.RenderPartial("BlogPost", Model, new ViewDataDictionary{ {"ForPrinting", "true"} });%>
Monsignor
  • 2,671
  • 1
  • 36
  • 34
11

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 }) %>
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
  • +1 for showing how to create/modify the ViewDataDictionary, but not a fan of taking a strongly typed method and using instead a more loosely typed one just to avoid declaring the ViewDataDictionary. If you get used to using RenderPartialWithData, but then you need other overloads of RenderPartial, you have to create even more overloads of your own method. It is clever, but I feel like you might be setting yourself up for more work rather than less. – AaronLS Nov 01 '12 at 21:38
3

You can do:

new ViewDataDictionary(new { ForPrinting = True })

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

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • 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 Mains Jan 22 '10 at 15:01
  • Yes, with RouteValuesDictionary you can do it. – Pablo Fernandez Jan 22 '10 at 15:04
0

This is not exactly what you asked for, but you can use 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;
}
Daniel Dušek
  • 13,683
  • 5
  • 36
  • 51