Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing anonymous objects from a view to a partial view

Tags:

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.

like image 530
Andy McCluggage Avatar asked Feb 16 '12 16:02

Andy McCluggage


People also ask

Can we use model in partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.

What objects are anonymous objects?

An anonymous object is basically a value that has been created but has no name. Since they have no name, there's no other way to refer to them beyond the point where they are created. Consequently, they have “expression scope,” meaning they are created, evaluated, and destroyed everything within a single expression.


1 Answers

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.

like image 83
adeel41 Avatar answered Oct 13 '22 04:10

adeel41