Can I pass an anonymous type to my ASP.NET MVC view?
Can you pass it to the view? Yes, but your view won't be strongly typed. But the helpers will work. For example:
public ActionResult Foo() {
return View(new {Something="Hey, it worked!"});
}
//Using a normal ViewPage
<%= Html.TextBox("Something") %>
That textbox should render "Hey, it worked!" as the value.
So can you define a view where T is defined by what gets passed to it from the controller? Well yes, but not at compile time obviously.
Think about it for a moment. When you declare a model type for a view, it's so you get intellisense for the view. That means the type must be determined at compile time. But the question asks, can we determine the type from something given to it at runtime. Sure, but not with strong typing preserved.
How would you get Intellisense for a type you don't even know yet? The controller could end up passing any type to the view while at runtime. We can't even analyze the code and guess, because action filters could change the object passed to the view for all we know.
I hope that clarifies the answer without obfuscating it more. :)
You can pass anonymous types to a view, just remember to cast the model to a dynamic.
You can do like this:
return View(new {
MyItem = "Hello",
SomethingElse = 42,
Third = new MyClass(42, "Yes") })
In the top of the view you can then do this (using razor here)
@{
string myItem = (dynamic)Model.MyItem;
int somethingElse = (dynamic)Model.SomethingElse;
MyClass third = (dynamic)Model.Third;
}
Or you can cast them from the ViewData like this:
@{
var myItem = ViewData.Eval("MyItem") as string
var somethingElse = ViewData.Eval("SomethingElse") as int?
var third = ViewData.Eval("Third") as MyClass
}
On .NET 4.0 Anonymous types can easily be converted to ExpandoObjects and thus all the problems is fixed with the overhead of the conversion itself. Check out here
For what it's worth, tonight I discovered the DataLoadOptions class and its LoadWith method. I was able to tell my LINQ to SQL DataContext to always load a Customers row whenever an Orders row is retrieved, so the original query now gets everything I need in one hit.
Here is an article explaining about passing Anonymous type to Views and binding the data.
Thanks