Vikas
Vikas

Reputation: 24322

How to access anonymous type returned by controller in view?

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?

Upvotes: 2

Views: 519

Answers (2)

Andrew Csontos
Andrew Csontos

Reputation: 662

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

Upvotes: 1

John Leidegren
John Leidegren

Reputation: 60987

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.

Upvotes: 1

Related Questions