Dynamic type in mvc mode

Possible duplicate:
Dynamic Anonymous Type in Razor Raises RuntimeBinderException

I am trying to use a dynamic type model in my MVC application. I have the following code: in the controller:

var model = new { Name = "test name", Family = "m" }; return this.View(model); 

and in my view:

 @model dynamic @if(Model!=null) { <p> @Html.Raw(Model.Name) </p> } 

When I run this, I get the following error:

 'object' does not contain a definition for 'Name' (System.Exception {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) 

Why am I getting this error? During debugging, if I place the cursor on @Model, I see that it has two properties, Name and Family.

+6
source share
1 answer

What you showed is not a dynamic type. This is an anonymous type. There is a huge difference.

You cannot use anonymous types as models. The reason for this is that the compiler generates anonymous types as internal . This means that they are only available with the current assembly. But, as you know, Razor views are compiled in the ASP.NET runtime environment as separate assemblies that cannot use these 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 your controller action will 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 used ViewBag , and so 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> 
+16
source

Source: https://habr.com/ru/post/905716/


All Articles