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. 

 

Published Wednesday, February 3, 2010 12:39 AM by shiju
Filed under: , ,

Comments

# re: ASP.NET MVC View Model object using C# 4 dynamic and ExpandoObject

Wednesday, February 3, 2010 1:54 AM by ali62b

If you’re using ReSharper, you will get Intellisense once you’ve declared a property once (both in the Action as well as the View).

devlicio.us/.../dynamic-types-and-asp-net-mvc.aspx

hadihariri.com/.../Dynamic-objects-and-ReSharper.aspx

# re: ASP.NET MVC View Model object using C# 4 dynamic and ExpandoObject

Wednesday, February 3, 2010 4:01 AM by shiju

@ali62b Thanks for the information

# re: ASP.NET MVC View Model object using C# 4 dynamic and ExpandoObject

Thursday, April 8, 2010 5:05 PM by Anonymous

Can someone add this?

Leave a Comment

(required) 
(required) 
(optional)
(required)