2013-06-26 21 views
1

我需要顯示一個數據表,可以返回一個視圖中可變數量的列,所以我綁定Mvc 3 WebGrid到列表<動態>,正如本文回答中所述:Populate MVC Webgrid from DataTableasp.net mvc 3 webgrid綁定到列表<dynamic>是非常緩慢

它工作正常,但速度令人難以置信! 「令人難以置信的慢」我的意思是需要13秒來顯示一組15列11列的記錄。有什麼辦法可以加快速度嗎?我嘗試刪除尋呼機,但沒有任何效果。

從Ado.Net數據表創建列表<動態>的代碼如下所示。它運行速度非常快,在這裏沒有問題。

var MyList = new List<dynamic>(); 
foreach (DataRow row in MyTable.Rows) 
{ 
    var expando = (IDictionary<string, object>)new ExpandoObject(); 
    foreach (string column in columnNames) 
    { 
     expando.Add(column, row[column]); 
    } 
    MyList.Add(expando); 
} 

問題出現在視圖中。下面的代碼需要大約13秒來呈現一組包含11列的15條記錄!到數據庫的行程和將數據錶轉換爲列表<動態>需要不到一秒的時間。下面的代碼需要13秒,只是爲了渲染。我究竟做錯了什麼?或者我只是使用列表<動態>吠叫錯誤的樹?

var grid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: false); 
grid.Bind(Model.MyList, rowCount: (int)Model.RowCount, autoSortAndPage: false); 
grid.Pager(WebGridPagerModes.All); 
       @grid.GetHtml(tableStyle: "webgrid", 
        rowStyle: "webgrid-row", 
        alternatingRowStyle: "webgrid-alternating-row", 
         htmlAttributes: new { id = "tblSearchResults" }, 
         firstText: "<<First", 
         lastText: "Last>>", mode: WebGridPagerModes.All 
       ) 

回答

4

我有同樣的問題,這是非常惱人的,因爲我們正在加載任意數據。

此修復程序是爲這些列定義列和格式函數,這改善了WebGrid的性能,並且性能比未定義格式更好(基於列數)。

例如

IEnumerable<KeyValuePair<string, Object>> example = data.First(); 
foreach (var pair in example) 
    cols.Add(grid.Column(
     columnName: pair.Key, 
     //Seems that specifying a formatter saves the web grid ridiculous amounts of time 
     format: (item => ((IDictionary<String, Object>)item.Value)[pair.Key]) 
    )); 

查看我的小示例項目https://github.com/jamesk/MVCWebGridSpeedTest以瞭解速度比較和完整示例代碼。

2

您是否曾經整理出過這個問題?我們放棄了使用for循環創建CSS樣式的列標題和行數據的WebGrid。 @Helper函數是關鍵,並且老實說它更容易控制。表現非常好。

  <table id="moduleGrid" summary="@tableSummary"> 
       <caption>@tableCaption</caption> 
       <thead> 
        <tr> 
         @GridColumnHeaders() 
        </tr> 
       </thead> 
       <tbody> 
        @GridDataRows() 
       </tbody> 
      </table> 
+0

不,我從來沒有辦法讓List 工作可以接受。按照你描述的同樣的解決方法創傷。 –