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>
source share