存储ViewBag一个匿名对象 [英] Storing an Anonymous Object in ViewBag

查看:583
本文介绍了存储ViewBag一个匿名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我想的东西,在 ViewBag 一个匿名对象,像这样:

This is probably a silly question, but I am trying to stuff an anonymous object in ViewBag like so:

ViewBag.Stuff = new { Name = "Test", Email = "user@domain.com" };

和来自像这样一个视图访问它:

and access it from a View like so:

@ ViewBag.Stuff.Name

@ViewBag.Stuff.Name

我明白ViewBag是动态的,是东西是一个匿名对象......但是当我看从上面的视图线调试器,我可以看到所有的正确值的属性。为什么模型绑定有这样的困难时期呢?

I understand ViewBag is dynamic and that "Stuff" is an anonymous object... but when I look with the debugger from the View line above, I can see all the properties with the proper values. Why does the model binder have such a hard time with this?

有没有做到这一点,而无需创建模型类的好办法?我想继续使用新{}

Is there a good way to accomplish this without creating a model class? I want to continue using new {}

推荐答案

本质的问题是,匿名类型是内部产生(的见回答),使得硬盘类型引用从视图对象的属性是不可能的。本文提供了一个更详细的解释:

Essentially the issue is that anonymous types are generated as internal (see answer), making hard typed references to the object's property impossible from the View. This article provides a more detailed explanation:

<一个href=\"http://www.heartysoft.com/anonymous-types-c-sharp-4-dynamic\">http://www.heartysoft.com/anonymous-types-c-sharp-4-dynamic

这可能与使用动态匿名包装类(@ Dakill的答案)来完成,但得到丑陋快,应该让程序员问题,为什么他/她会这么做。

It is possible to accomplish with the use of a Dynamic Anonymous wrapper class (@Dakill's answer), but gets ugly fast and should make a programmer question why he/she would do so.

这篇关于存储ViewBag一个匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆