Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 将ViewData传递给RenderPartial_Asp.net Mvc_Renderpartial - Fatal编程技术网

Asp.net mvc 将ViewData传递给RenderPartial

Asp.net mvc 将ViewData传递给RenderPartial,asp.net-mvc,renderpartial,Asp.net Mvc,Renderpartial,我正在尝试调用此方法: RenderPartialExtensions.RenderPartial Method (HtmlHelper, String, Object, ViewDataDictionary) 但我看不到任何在表达式中构造ViewDataDictionary的方法,如: <% Html.RenderPartial("BlogPost", Post, new { ForPrinting = True }) %> 有什么办法吗?你可以: new ViewDat

我正在尝试调用此方法:

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

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

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

有什么办法吗?

你可以:

new ViewDataDictionary(new { ForPrinting = True })

正如viewdatadictionary可以在其构造函数中对对象进行反射一样。

我已经通过以下扩展方法实现了这一点:

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

这对我很有用:

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

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

你说得对,我道歉。我在想RouteValuesDictionary,虽然这个函数的名字很奇怪,但是你可以用它作为新的RouteValuesDictionary(new{..}),这会提取属性值并使它们成为单独的键/值对,然后你可以将它们传递给viewdatadictionary实例。是的,使用RouteValuesDictionary,您可以执行此操作。+1用于显示如何创建/修改ViewDataDictionary,但不喜欢使用强类型方法,而是使用更松散的类型方法,以避免声明ViewDataDictionary。如果您习惯于使用RenderPartialWithData,但是需要RenderPartial的其他重载,那么您必须为自己的方法创建更多重载。这很聪明,但我觉得你可能在为自己安排更多的工作,而不是更少的工作。