how to bind datatable to webgrid using MVC?

亡梦爱人 提交于 2019-12-11 03:51:08

问题


This is my first post. help me. how to bind datatable to webgrid? My code:

SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("select * from candidate", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return View(dt);

I want to bind datatable to webgrid..help me...


回答1:


This is best solution I found :) hope it can help you:

SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("select * from candidate", con);

DataTable dt = new DataTable();
SqlDataAdapter a = new SqlDataAdapter(cmd)
a.Fill(dt);

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

WebGrid grid = new WebGrid(Model, canPage: true, rowsPerPage: 15);

Then in view you can use:

@grid.GetHtml(htmlAttributes: new { id = "empTable" },
            tableStyle: "table table-striped table-hover",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            columns: grid.Columns(
                grid.Column("col1name", "Column title"),
                grid.Column("col2name", "Column2 title")
     ))

where grid is your WebGrid grid variable.




回答2:


I had to use a DataTable as the data was coming from 3rd party code via a DataTable. I had issues getting WebGrid to detect/reflect columns that were added to the DataTable. Converting to a dynamic list as per mrfazolka's answer worked. I ended up making it into a static method:

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


来源:https://stackoverflow.com/questions/18489974/how-to-bind-datatable-to-webgrid-using-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!