Trang chủ » ASP.NET MVC » Small tip with dynamic type view in ASP.MVC 2

Small tip with dynamic type view in ASP.MVC 2

ASP.NET MVC 2 allows you use dynamic type view by using System.Web.Mvc.ViewPage<dynamic> (or someone call this case is anonymous type view). When you use dynamic type view, the Model property is a dynamic-object which is resolved at the runtime.

But, you will meet something wrong when you use dynamic type view. Example, Display is a dynamic type view in my ASP.NET MVC 2 Web Application. And in my action, I do something like this

Code Snippet
  1. return View("Display",
  2.     new
  3.     {
  4.         Mode = "Error",
  5.         Message = "This Student ID has already registered by someone."
  6.     });

I return Display view and pass an anonymous object as a model to Display view. And this is my Display view

Code Snippet
  1. <div>
  2.     <%: Model.Mode %>
  3.     <%: Model.Message %>
  4. </div>

Everything looks good. But, when you run this application and navigate to Display view, you will get RuntimeBinderException exception with message {‘object’ does not contain definition for ‘Mode’}. And it’s more crazy when you switch to debug mode and watch Model property, there are existing Mode and Message properties! So, what’s wrong here?

The answer is Anonymous type is internal, it means its properties, methods can’t be access from outside its assembly. (You can read more explaination at

The solution for my case is very simple like this

Code Snippet
  1. <div>
  2.     <%: Model.GetType().GetProperty("Mode").GetValue(Model, null) %>
  3.     <%: Model.GetType().GetProperty("Message").GetValue(Model, null)%>
  4. </div>

And everything working well.


Bình luận

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập: Logo

Bạn đang bình luận bằng tài khoản Đăng xuất /  Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất /  Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất /  Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất /  Thay đổi )


Connecting to %s