我正在尝试调用此方法:
RenderPartialExtensions.RenderPartial Method (HtmlHelper, String, Object, ViewDataDictionary)
http://msdn.microsoft.com/en-us/library/dd470561.aspx
但我没有看到在表达式中构造ViewDataDictionary的任何方法,例如:
<% Html.RenderPartial("BlogPost", Post, new { ForPrinting = True }) %>
任何想法如何做到这一点?
答案 0 :(得分:24)
这对我有用:
<% Html.RenderPartial("BlogPost", Model, new ViewDataDictionary{ {"ForPrinting", "true"} });%>
答案 1 :(得分:10)
我已设法使用以下扩展方法执行此操作:
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 }) %>
答案 2 :(得分:3)
你可以这样做:
new ViewDataDictionary(new { ForPrinting = True })
由于viewdatadictionary可以使对象在其构造函数中反映出来。
答案 3 :(得分:0)
这不是您要求的,但您可以使用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;
}