Passing anonymous objects from a view to a partial view

Andy McCluggage picture Andy McCluggage · Feb 16, 2012 · Viewed 11.6k times · Source

I understand from various other related questions here and here among others, that you can't pass anonymously typed objects from the controller to the view because anonymous types are defined with the Internal accessor. The View and Controller code are compiled into different assemblies so attempting to use it results in this error...

object does not contain a definition for 'foo'

That is fine and I can accept that, although it was annoying at first. There are enough suggested workarounds to appease me.

However, I thought you would still be able to pass an anonymous type from a view to a partial view because, both being views, they would be compiled in the same assembly.

Razor View code...

@Html.Partial("Partial1", new { foo = "Something", bar = "Something else" })

and the partial view code for "Partial1"

@model dynamic 

<h1>@Model.foo</h1>
<span>@Model.bar</span>

The strange thing is, this WAS working at the beginning of a the development on a new MVC project, but as I added more views it just stopped working and now give me the same error that I mentioned above.

It is as if I have reached a threshold where the view and partial view are no longer compiled into the same assembly. But I'm just guessing.

I wonder if anyone can shed any light of this.

Answer

adeel41 picture adeel41 · Sep 17, 2013

Don't know the reason why it stopped working but here is the workaround.

Use @ViewData.Eval("foo") instead of @Model.foo

and remove your @model dynamic line. There is no need of it.