如何使用MVC将数据表绑定到Webgrid? [英] how to bind datatable to webgrid using MVC?

查看:86
本文介绍了如何使用MVC将数据表绑定到Webgrid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章.帮我.如何将数据表绑定到Webgrid? 我的代码:

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);

我想将数据表绑定到webgrid ..帮助我...

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

推荐答案

这是我发现的最好的解决方法:)希望它可以为您提供帮助:

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")
     ))

其中grid是您的WebGrid grid变量.

where grid is your WebGrid grid variable.

这篇关于如何使用MVC将数据表绑定到Webgrid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆