Подтвердить что ты не робот

Pass ViewData для RenderPartial

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

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

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

но я не вижу никакого способа построить ViewDataDictionary в выражении, например:

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

Любые идеи, как это сделать?

4b9b3361

Ответ 1

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

<% Html.RenderPartial("BlogPost", Model, new ViewDataDictionary{ {"ForPrinting", "true"} });%>

Ответ 2

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

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

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

new ViewDataDictionary(new { ForPrinting = True })

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

Ответ 4

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