views:

810

answers:

4

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.

+2  A: 

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.

Marc Gravell
Not really. There are evil ways of casting an anonymous type and getting type safe access. http://blogs.msdn.com/jaredpar/archive/2007/10/01/casting-to-an-anonymous-type.aspx
JaredPar
@JaredPar: OK, doable:yes - but desirable?
Marc Gravell
+2  A: 

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

Darin Dimitrov
+1  A: 

I believe you want to at least give them names:

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


view(model);
Todd Smith
+3  A: 

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 %>

Haacked