I wrote a List`1 editor template for use with the EditorFor (MVC2) extension methods, however I ran into problems when using generics + null objects.
Given the model
class MyModel {
public Foo SomeFoo { get;set; }
public List<Foo> SomeFooList { get;set; }
}
and template in / Views / Shared / EditorTemplates / List `1.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
IEnumerable enumerableModel;
if (Model != null && (enumerableModel = Model as IEnumerable) != null)
{
foreach (var v in enumerableModel)
{
var model = v;
Response.Write(Html.EditorFor(m => model));
}
}
%>
I get the expected editor for SomeFoo and any SomeFooList elements that are not null, since the type in ModelMetaData will be "Foo". However, if I have βzeroβ as one of the objects in SomeFooList, I get nothing, because the model is of type βobjectβ, and not Foo or the more general T from my general list arguments.
Essentially, I would like to achieve something like
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<T>> where T : class" %>
so I know the types of my list.
ModelMetaData.ModelType null ( , ), , .
EditorFor .Invoke typeof (T) , , , .
?
Update:
, . , , , , , :
if (Model != null && (enumerableModel = Model as IEnumerable) != null)
{
Type listType = null;
if (enumerableModel.GetType().IsGenericType)
{
listType = enumerableModel.GetType().GetGenericArguments()[0];
}
foreach (var v in enumerableModel)
{
var model = v;
if (model == null && listType != null)
model = Activator.CreateInstance(listType);
Response.Write(Html.EditorFor(m => model));
}
}