这是我找到的最佳解决方案:) 希望它可以帮助您:
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);
然后在视图中您可以使用:
@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")
))
其中 grid 是你的WebGrid grid
变量。