1

I have an MVC application where I need to be able to display various records in a view. For this, I went the route of using the built in Webgrid control. The problem I faced was taking my data from my Datatable returned from the database and converting it into an IEnumerable for the grid. I came across a method on SO to convert it to a type of List Dynamic which seemed to work well enough, but encountered issues when displaying more than about 6 columns of data:

public static dynamic serializeToDynamic(DataTable dt)
    {
        var result = new List<dynamic>();
        foreach (System.Data.DataRow row in dt.Rows)
        {
            var obj = (IDictionary<string, object>)new System.Dynamic.ExpandoObject();
            foreach (System.Data.DataColumn col in dt.Columns)
            {
                obj.Add(col.ColumnName, row[col.ColumnName]);
            }
            result.Add(obj);
        }
        return result;
    }

I have a grid that needs to display 28 columns and using this method is extremely slow, with the page taking close to a minute to load. I was unsuccessful in finding any alternatives, so I went ahead and made a model for this information and bound the DataTable to this model which proved to be much faster loading in about 2 seconds. I'd rather not have to use strongly typed models just to display this data, my question is is there any other method to convert a DataTable to work with a webgrid?

tereško
  • 58,060
  • 25
  • 98
  • 150
user2838580
  • 11
  • 1
  • 2
  • This is a duplicate of http://stackoverflow.com/questions/17322239/asp-net-mvc-3-webgrid-bound-to-listdynamic-is-exceedingly-slow which I have answered. – James k Jan 15 '14 at 10:00

3 Answers3

0

If all you need is an IEnumerable of any type then you can use the DataTableExtensions:

var result = dt.AsEnumerable();

That would give you an IEnumerable<DataRow>, which still doesn't carry the benefits of strongly typed objects but is at least an IEnumerable.

David
  • 208,112
  • 36
  • 198
  • 279
0

This question is seemingly a duplicate of asp.net mvc 3 webgrid bound to List<dynamic> is exceedingly slow which I have just answered.

Community
  • 1
  • 1
James k
  • 242
  • 2
  • 8
0

This ends up being pretty straight-forward. Notice the With extension function.

@model DataTable

@{
    var columns = Model.Columns.Cast<DataColumn>().Select(c => c.ColumnName);
    var s = Model.Rows.Cast<DataRow>().Select(r => new System.Dynamic.ExpandoObject().With(columns.ToDictionary(c => c, c => r[c])));
    WebGrid grid = new WebGrid(s, rowsPerPage: 10);
  }

Since ExpandoObject is a dictionary, you can use this extension function:

public static object With(this IDictionary<string, object> obj, IDictionary<string,object> additionalProperties)
{
  foreach (var name in additionalProperties.Keys)
    obj[name] = additionalProperties[name];
  return obj;
}
toddmo
  • 20,682
  • 14
  • 97
  • 107