gpt4 book ai didi

c# - 如何访问传递到局部 View 的匿名类型对象?

转载 作者:行者123 更新时间:2023-11-30 22:31:06 24 4
gpt4 key购买 nike

我正在尝试将一些参数(几个字符串)从页面传递到要在主页中呈现的局部 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com