我正在尝试将一些参数(几个字符串)从页面传递到要在主页中呈现的部分 View 。为此,我传递了一个匿名类型的对象,该对象不断地向我抛出 RuntimeBinderException。根据我的尝试,我对收到错误并不感到惊讶,但我不知道还可以尝试什么。
Views\Home\PageWithPartialView.cshtml
@Html.Partial("DynamicPartialView", new { paramFromPageToPartialView = "value" })
Views\Shared\DynamicPartialView.cshtml
@model dynamic // Doesn't make a difference
@{
// This is where I need to access and display the parameters
// passed from the main page
// Throws RuntimeBinderException
// Cannot apply indexing with [] to an expression of type 'object'
var try1 = Model["paramFromPageToPartialView"];
// Throws RuntimeBinderException
// 'object' does not contain a definition for 'paramFromPageToPartialView'
var try2 = Model.paramFromPageToPartialView;
}
如果部分 View 不是实现此目的的方法,我愿意。部分 View 需要生成几百行代码,因此自定义 HtmlHelpers 对我来说似乎无法管理。
最佳答案
ViewBag
就是为了解决此类问题而设计的。不要从模型中使用部分中的 paramFromPageToPartialView
,而是从 ViewBag
中使用它:
Views\Home\PageWithPartialView.cshtml
@{ViewBag.paramFromPageToPartialView = "value";}
@Html.Partial("DynamicPartialView")
Views\Shared\DynamicPartialView.cshtml
@model dynamic // Doesn't make a difference
@{
var try3 = ViewBag.paramFromPageToPartialView;
}
关于c# - 如何访问传递到部分 View 中的匿名类型对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9402072/