zsharp
zsharp

Reputation: 13756

Is it safe to pass anonymous type to MVC ViewData.Model?

Is it ok to do the following:

View(new {Object A, Object B})

Or should Object A and Object B be explicitly declared in a new type?

Thanks.

Upvotes: 1

Views: 2096

Answers (4)

Haacked
Haacked

Reputation: 59001

Yes, it's fine to do so. To get the values, you can use ViewData.Eval("PropertyName") and the existing Html helpers will work fine with them. The only thing you won't be able to do is get strongly typed access to the properties using <%= ViewData.Model.PropertyName %>

Upvotes: 4

Todd Smith
Todd Smith

Reputation: 17272

I believe you want to at least give them names:

var model = new 
{
    ObjectA = new A(),
    ObjectB = new B(),
};


view(model);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038740

By passing anonymous types you cannot have strongly typed views. You will also need to use reflection in your unit tests.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062745

Although anonymous types are versatile for many MVC purposes, in this case I would use a regular named class, or at a push a dictionary (or the inbuilt one). Otherwise you will have to use reflection / TypeDescriptor to get the values out again.

Upvotes: 2

Related Questions