title: passing dynamic model in MVC5 Razor View
body: <p>I'm trying to pass dynamic results to View from Controller, method <code>ShowColor</code> returns dynamic results.  In View I try to loop through the collection but I'm getting error </p>
  
  <blockquote>
    <p>'object' does not contain a definition for 'ColorID'.</p>
  </blockquote>
  
  <p>I have the following code in Controller and View</p>
  
  <pre><code>public class myColor
  {
      public int ID { get; set; }
      public string  Name { get; set; }
      public string Like { get; set; }
  }
  
  public dynamic ShowColor()
  {
      IList&lt;myColor&gt; color = new List&lt;myColor&gt;();
      color.Add(new myColor { ID = 1, Name = "Red", Like = "***" });
      color.Add(new myColor { ID = 2, Name = "Green", Like = "*****" });
      color.Add(new myColor { ID = 3, Name = "Blue", Like = "**" });
      color.Add(new myColor { ID = 4, Name = "Yellow", Like = "*" });
  
      var select = (from c in color
                    select new
                    {                     
                        ColorID = c.ID,
                        ColorName = c.Name
                    }).ToList();
  
      return select;
  }
  public ActionResult DBDynamic()
  {
      return View(ShowColor());
  }
  </code></pre>
  
  <p>View</p>
  
  <pre><code>@model dynamic
  
  @{
      ViewBag.Title = "DBDynamic";
  }
  
  &lt;h2&gt;DBDynamic&lt;/h2&gt;
  
  &lt;p&gt;
      &lt;ul&gt;
          @foreach (var m in Model)
          {
              &lt;li&gt; @m.ColorID&lt;/li&gt;            
          }
      &lt;/ul&gt;
  
  &lt;/p&gt;
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/I5LLt.jpg" alt="Error"></p>
  
  <p><img src="https://i.stack.imgur.com/lhjmQ.jpg" alt="Debug Image"></p>
  
  <p><strong>Found the solution</strong> <a href="http://www.dotnetfunda.com/articles/show/2655/binding-views-with-anonymous-type-collection-in-aspnet-mvc" rel="nofollow noreferrer">here</a> and a nice blog <a href="https://blogs.msdn.microsoft.com/davidebb/2009/12/18/passing-anonymous-objects-to-mvc-views-and-accessing-them-using-dynamic/" rel="nofollow noreferrer">here</a>:</p>
  
  <pre><code>public static ExpandoObject ToExpando(this object anonymousObject)
  {
      IDictionary&lt;string, object&gt; expando = new ExpandoObject();
      foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
      {
          var obj = propertyDescriptor.GetValue(anonymousObject);
          expando.Add(propertyDescriptor.Name, obj);
      }
  
      return (ExpandoObject)expando;
  }
  </code></pre>
  
  <p>And call it like this</p>
  
  <pre><code>    var select = (from c in color
                  select new
                  {
                      ColorID = c.ID,
                      ColorName = c.Name
                  })
                  .AsEnumerable()
                  .Select(x =&gt; x.ToExpando());
  
  return View(select);
  </code></pre>