Search code examples
asp.net-mvclinqanonymous-typesviewdata

LINQ Anonymous Types + MVC Views


I've seen many questions about this, but i've never really got the answer that I need.

I'm converting a fairly large web application from Web Forms to MVC and after a while I encountred a problem with passing data to the view. In the Action I execute the code:

//This is just an example ViewData["QProducts"] = from p in db.Products select new{Name = p.Name, Date = p.ToShortDateString() } ViewData["QUsers"] = from u in db.Users select u;

I use a foreach loop to iterate over the objects in html, like this:

foreach(var q in (IEnumerable)ViewData["QEvents"])
{ 
    /*Print the data here*/
}

Before using MVC I just used a asp:Repeater, but since this is MVC I can't use ASP.NET controls.

How am I supposed to pass this data to the View? I don't really have the option of not using Anonymous Types here. <%#ViewData.Eval()%> obviously won't work.

Any Ideas?


Solution

  • Rather than an anonymous type, create a type to hold the name and date:

    public class NameDate
    {
      public string Name { get; set; }
      public DateTime Date { get; set; }
    }
    

    Then use that in your Linq query:

    from p in db.Products select new NameDate { Name = p.Name, Date = p.Date }
    

    Strongly type your view to be MyView<IEnumerable<NameDate>> and then just do a foreach ( var nameDate in ViewData.Model )...