DataTable转为json并绑定Easyui的datagrid控件

来源:互联网 发布:sql删除有约束字段 编辑:程序博客网 时间:2024/05/29 18:01
最近突然对EasyUi的crud比较感兴趣,于是到它们官网看了看Demo,发 现easyui的crud操作还是比较简单的,但是由于easyui封装的比较紧密这就造成了我们不容易理解。 我们先从显示界面分析其Html代码:<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"    url="get_users.ashx"    toolbar="#toolbar" pagination="true"    rownumbers="true" fitColumns="true" singleSelect="true">    <thead>        <tr>            <th field="firstname" width="50">First Name</th>            <th field="lastname" width="50">Last Name</th>            <th field="phone" width="50">Phone</th>            <th field="email" width="50">Email</th>        </tr>    </thead></table><div id="toolbar"><a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a><a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a><a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a></div>在这里我先介绍属性url,url写入的地址(即从该地址进入后台获取数据),然后再通过field属性绑定数据。了解到这里我们会发现碰到一个问题:就是从后台读取数据直接返回的话,我们会发现数据并没有绑定datagrid,分析原因是js只能接收json类型数据,这里就要求我们将后台获取的数据转为json格式再返回到前台。后台我是通过数据库操作返回一个DataTable类型的,这里就要求我们将DataTable类型转化为json类型具体代码如下:StringBuilder json = new StringBuilder();DataTable dt = GetTable(); json.Append("[");      if (dt.Rows.Count > 0)        {           for (int j = 0; j < dt.Rows.Count; j++)            {                json.Append("{");                for (int i = 0; i < dt.Columns.Count; i++)                {                    json.Append(string.Format("\"{0}\":\"{1}\",", dt.Columns[i].ColumnName, dt.Rows[j][i].ToString()));                }                json.Remove(json.ToString().LastIndexOf(","),1);                json.Append("}");                json.Append(",");            }           }        json.Remove(json.ToString().LastIndexOf(","), 1);        json.Append(']');        Response。write(json);

效果如下图所示:
这里写图片描述
暂时就写到这了,小弟第一次写技术贴不容易,表达不好望见谅,如果有讲错的地方请多多指教,大家一起进步。

0 0
原创粉丝点击