如何在视图的 ViewBag 中访问动态对象成员

How can I access dynamic object members in ViewBag of view

我已经在带有动态对象的 actionresult 中分配了 ViewBag,如​​下所示

ViewBag.viewBagModel = new { code = "P8c93E0NlQ8c0xE=", userRole = Student, schoolCode = 1000, schoolName = "New School 1_change", standardName = "LKG", sectionName = "B", associatedStudent = null }

而且我可以在 controller/actionresult 中按名称获取值,例如:

ViewBag.viewBagModel.code // will return "P8c93E0NlQ8c0xE="

但是当我在 View 中尝试相同时,我收到错误消息

"{"'object' does not contain a definition for 'code'"}"

更多信息:此动态对象的语法

new {string code, string userRole, int? schoolCode, string schoolName, string standardName,string sectionName, string user}

我希望在视图中获取此对象数据。

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

您的视图模型必须是 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 方法的静态 class:

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;
        }
    }

使用 ToString() 扩展名。我现在确实尝试过,它似乎有效。话虽如此,我建议您使用非动态模型。即使你已经有一个 View 的模型,你也可以把它放在另一个模型中。

因此您的代码将如下所示

ViewBag.viewBagModel.code.ToString();