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.
Strongly typed views are very useful in MVC for rendering model data on page and binding the properties with the input fields. Moreover, strongly typed views give intellisense support, so that we can choose the right property name for the control.
Strongly typed views are used for rendering specific types of model objects, instead of using the general ViewData structure. By specifying the type of data, you get access to IntelliSense for the model class.
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:
public class MyViewModel
{
public string Name { get; set; }
public string Family { get; set; }
}
and then have your controller action pass this view model to the view:
var model = new MyViewModel { Name = "test name", Family = "m" };
return this.View(model);
so that your view can work with it:
@model MyViewModel
@if (Model != null)
{
<p>@Model.Name</p>
}
Some people (not me, I would never recommend anything like this) also use ViewBag
and this way they don't need a model:
ViewBag.Name = "test name";
ViewBag.Family = "m";
return this.View();
and then in the view:
<p>@ViewBag.Name</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With