c# - 如何访问 ViewBag 中的动态对象成员
问题描述
我已经在 actionresult 中为 ViewBag 分配了动态对象,如下所示
ViewBag.viewBagModel = new { code = "P8c93E0NlQ8c0xE=", userRole = Student, schoolCode = 1000, schoolName = "New School 1_change", standardName = "LKG", sectionName = "B", associatedStudent = null }
我可以在控制器/actionresult 中按名称获取值,例如:
ViewBag.viewBagModel.code // will return "P8c93E0NlQ8c0xE="
但是当我在 View 中尝试相同时,我收到错误说明
"{"'object' 不包含'code'的定义"}"
更多信息:这个动态对象的语法
new {string code, string userRole, int? schoolCode, string schoolName, string standardName,string sectionName, string user}
我希望在 View 中获取此对象数据。
解决方案
您的对象是匿名类型。您将无法直接在视图中访问它。你仍然可以让它以不同的方式工作。
您的视图模型需要是类型dynamic
:
@model IEnumerable<dynamic>
然后将模型的代码更改为如下类型ExpandoObject
:
ViewBag.viewBagModel = new { code = "P8c93E0NlQ8c0xE=", userRole = Student, schoolCode = 1000, schoolName = "New School 1_change", standardName = "LKG", sectionName = "B", associatedStudent = null }.ToExpando();
注意.ToExpando()
以上。这是带有该ToExpando
方法的静态类:
public static class Extensions
{
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
}
推荐阅读
- python - 根据熊猫数据框中的另一列获取名称
- vba - VBA cval 和 pval
- swiftui - SwiftUI检测删除按钮被按下
- python - 无法将任务添加到待办事项列表
- django - Django 测试:类型对象没有属性“对象”
- javascript - 简单的cookie测试
- swift - Swift 5 / Swift UI 中的随机 URL
- python - Python - 如果满足 csv 文件中的条件,则添加时间戳列
- inheritance - 有没有办法根据用户选择更改 Blazor EditForm 组件上的模型?
- python - 在 tkinter 中迭代显示图像