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. 🙂

Leave a Comment