tags:

views:

95

answers:

2

In MVC RC2 I am returning an anonymous object type & I want to access it in a strongly typed view. Let's say that in the controller I query the database & fetch values in var type & I want to pass it to a strongly typed view. How can i access it in that view?

+1  A: 

Well, you can't. An anonymous type, cannot be accessed by name. That's the whole point. You can't pass the type around, the type exist internally and you can only expose the type as System.Object.

You can always use reflection to dig up the properties and access them that way, but other than that, there's not way around it.

var q = new { MyProperty = "Hello World" };
var t = q.GetType();
var hello = t.GetProperty("MyProperty").GetValue(q, null) as string;
Console.WriteLine(hello);

If you need to access the type, you should create an user-defined object/type, which can be identified by name.

John Leidegren
A: 

You can't pass it to a strongly typed view, but you could turn it into a dictionary and access the properties that way.

As part of System.Web.Routing, there is a new object called "RouteValueDictionary", which can take as it's constructor an anonymous object.

The MVC team uses this in many of their helpers.

Example:

IDictionary<string, object> myDict = new RouteValueDictionary(anonymousObject);
Andrew Csontos