首页 > 解决方案 > 如何访问 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 中获取此对象数据。

标签: c#asp.net-mvcviewbag

解决方案


您的对象是匿名类型。您将无法直接在视图中访问它。你仍然可以让它以不同的方式工作。

您的视图模型需要是类型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;
        }
    }

推荐阅读