ASP.NET MVC2: Can you get ModelMetadata.ContainerType from within a collection?
- by CodeSponge
I'm trying to call DisplayFor and DisplayForModel to iterate an IEnumerable< with various element types from within a view. I have Templates defined for each element/Model type.
What I would like to do is check the ViewData.ModelMetadata.ContainerType from within the Template so that Template can determine if it was called as part of a collection.
A simple example:
Index1.aspx: To render a collection of Foos.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Foo>>" %>
<asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server">
<ul><%:Html.DisplayForModel()%></ul>
</asp:Content>
Index2.aspx: To render a Foo.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Foo>" %>
<asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server">
<%:Html.DisplayForModel()%>
</asp:Content>
Shared\DisplayTemplates\Foo.ascx: A context aware Template for Foo.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Foo>" %>
<% var tag = typeof(IEnumerable).IsAssignableFrom(ViewData.ModelMetaData.ContainerType) ? "li" : "div";
%> <<%:tag%>><%:Model.Name%></<%:tag%>>
The problem with this example is that ViewData.ModelMetaData.ContainerType is null in the Template when resolved though Index1.aspx. From what I've read on Brad Wilson post and others it has to do with the use of IEnumerable and its being an interface.
Is there a way to insure that the ContainerType is set? Perhaps by creating a ModelMetadataProviders? I looked into that breifly but it appears the ContainerType value is determined before and then passed to the Provider.
Any suggestions would be appreciated.