ASP.NET MVC View Model object using C# 4 dynamic and ExpandoObject
In my last post, I have explained the use of View Model objects in ASP.NET MVC applications. In this post, let me discuss on view model objects by using the C# 4 dynamic and ExpandoObject. I do not recommending to use dynamic keyword for creating View Model objects that will loss the intellisense feature of Visual Studio.
public ActionResult List() {
dynamic viewModel = new ExpandoObject();
viewModel.ContactGroup = contactRepository.ListGroups().ToSelectListItems(-1);
return View(viewModel);
}
The above action method creating a view model object with dynamic keyword and dynamically add a property ContactGroup for binding values to a drop-down list. At compile time, an element that is typed as dynamic is assumed to support any operation. The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members.
In our view page we are creating a strongly typed view with type dynamic
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
The Model.ContactGroup returns a type IEnumerable<SelectListItem> at runtime. Currently the HTML Helper Extension methods cannot be dynamically dispatched. So I am casting the ContactGroup property with IEnumerable<SelectListItem>.
<%=Html.DropDownList("GroupId", Model.ContactGroup as IEnumerable<SelectListItem>)%>
The purpose of the post is to explain the capabilities of dynamic keyword for creating strongly types views and I do not recommending to use dynamic keyword for creating View Model objects. This will loss the intellisense feature of Visual Studio and also affecting the maintainability.