asp.net-mvc 将 ViewData 传递给 RenderPartial

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2117367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:05:13  来源:igfitidea点击:

Pass ViewData to RenderPartial

asp.net-mvcrenderpartial

提问by pupeno

I'm trying to call this method:

我正在尝试调用此方法:

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

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

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

but I don't see any way to construct a ViewDataDictionary in an expression, like:

但我看不到在表达式中构造 ViewDataDictionary 的任何方法,例如:

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

Any ideas how to do that?

任何想法如何做到这一点?

回答by Monsignor

This worked for me:

这对我有用:

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

回答by pupeno

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 }) %>

回答by Brian Mains

You can do:

你可以做:

new ViewDataDictionary(new { ForPrinting = True })

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

由于 viewdatadictionary 可以采用一个对象在其构造函数中进行反射。

回答by dee

This is not exactly what you asked for, but you can use ViewContext.ViewBag.

这不是您所要求的,但您可以使用 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;
}