Передать ViewData в RenderPartial - PullRequest
       12

Передать ViewData в RenderPartial

16 голосов
/ 22 января 2010

Я пытаюсь вызвать этот метод:

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 ]

24 голосов
/ 04 ноября 2010

Это сработало для меня:

<% Html.RenderPartial("BlogPost", Model, new ViewDataDictionary{ {"ForPrinting", "true"} });%>
10 голосов
/ 22 января 2010

Мне удалось сделать это с помощью следующего метода расширения:

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 }) %>
3 голосов
/ 22 января 2010

Вы можете сделать:

new ViewDataDictionary(new { ForPrinting = True })

Поскольку viewdatadictionary может взять объект для отражения в своем конструкторе.

0 голосов
/ 11 июня 2013

Это не совсем то, что вы просили, но вы можете использовать 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;
}
...