title: ASP.NET MVC View / Partial with generics
body: <p>I have written a List`1 editor template for use with the EditorFor extension methods (MVC2), however I am running into issues when using generics + null objects.</p>
  
  <p>Given a model</p>
  
  <pre><code>class MyModel {
     public Foo SomeFoo { get;set; }
     public List&lt;Foo&gt; SomeFooList { get;set; }
   }
  </code></pre>
  
  <p>and a template in /Views/Shared/EditorTemplates/List`1.ascx</p>
  
  <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;
  
  &lt;%
      IEnumerable enumerableModel;
      if (Model != null &amp;&amp; (enumerableModel = Model as IEnumerable) != null)
      {
          foreach (var v in enumerableModel)
          {
              var model = v;
              Response.Write(Html.EditorFor(m =&gt; model));
          }
      }
  %&gt;
  </code></pre>
  
  <p>I get the expected editor for SomeFoo, and any elements of SomeFooList which are not null, as the type in ModelMetaData will be "Foo". However, if I have "null" as one of the objects in SomeFooList, I get nothing rendered as model is of type "object" and not Foo or more generically T from my list's generic arguments.</p>
  
  <p>Essentially I would like to achieve something like</p>
  
  <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;IEnumerable&lt;T&gt;&gt; where T : class" %&gt;
  </code></pre>
  
  <p>so I know the types of my list.</p>
  
  <p>I could also look at changing the ModelMetaData.ModelType field in the case of a null (by creating a new object, as this is readonly) -- but this is one of those nasty hacks I would like to avoid.</p>
  
  <p>Another thought is calling the EditorFor method with .Invoke and passing typeof(T) into there, but again, I would like to avoid this type of code if possible.</p>
  
  <p>Any thoughts?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Trying to get the type into model meta data was looking a little trickier than I first expected. I have updated my code with the following which seems to work, but I am still not too keen on the solition:</p>
  
  <pre><code>if (Model != null &amp;&amp; (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 &amp;&amp; listType != null)
                  model = Activator.CreateInstance(listType);
              Response.Write(Html.EditorFor(m =&gt; model));
          }
      }
  </code></pre>
  
  <p>Amar</p>