Possible Duplicate:
Dynamic Anonymous type in Razor causes RuntimeBinderException
I am trying to use a dynamic type model in my MVC application. I have the following code:
in controller:
var model = new { Name = "test name", Family = "m" };
return this.View(model);
and in the view I have:
@model dynamic
@if(Model!=null)
{
<p> @Html.Raw(Model.Name) </p>
}
When I am running this, I am getting the following error :
'object' does not contain a definition for 'Name' (System.Exception {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
Why do I get this error?
During debug, if I put my cursor on @Model, I can see that it has two property called Name and Family.
What you have shown is not a dynamic type. It’s an anonymous type. There’s a huge difference.
You cannot use anonymous types as models. The reason for this is because the compiler emits anonymous types as internal. This means that they are only accessible withing the current assembly. But as you know Razor views are compiled by the ASP.NET runtime as separate assemblies which have no way of using those anonymous types.
Obviously the correct way in this case is to use a view model:
and then have your controller action pass this view model to the view:
so that your view can work with it:
Some people (not me, I would never recommend anything like this) also use
ViewBagand this way they don’t need a model:and then in the view: