首先,我们创建一个User的实体类
public class User { public string UserID; public string UserName; public string Sex; }
public ActionResult test() { List<User> listUser = new List<User>(); listUser.Add(new User { UserID = "001", UserName = "呵呵", Sex = "男" }); listUser.Add(new User { UserID = "002", UserName = "哈哈", Sex = "女" }); listUser.Add(new User { UserID = "003", UserName = "嘿嘿", Sex = "男" }); ViewData["listUser"] = listUser; return View(); }
<div> <table id="dg" class="easyui-datagrid" style="width: 600px; height: 300px" > <thead> <tr> <th data-options="field:'UserID',width:148,sortable:true">ID</th> <th data-options="field:'UserName',width:148,sortable:true">姓名</th> <th data-options="field:'Sex',width:148,sortable:true">性别</th> </tr> </thead> @foreach (ITOO.EvaluationUI.Models.User enUser in ViewData["listUser"] as List<ITOO.EvaluationUI.Models.User>) { <tr> <td>@enUser.UserID </td> <td>@enUser.UserName </td> <td>@enUser.Sex </td> </tr> } </table> </div>
<div> <table id="dg" class="easyui-datagrid" style="width: 600px; height: 300px" > <thead> <tr> <th data-options="field:'UserID',width:148,sortable:true">ID</th> <th data-options="field:'UserName',width:148,sortable:true">姓名</th> <th data-options="field:'Sex',width:148,sortable:true">性别</th> </tr> </thead> </table> </div> <!--datagrid基本设置--> <script type="text/javascript"> $(function () { $('#dg').datagrid({ title: '测试表格', url: "/EvaluationSituation/jsonTest", pagination: true,//显示分页工具栏 }); }); </script>
public JsonResult jsonTest() { List<User> listUser = new List<User>(); listUser.Add(new User { UserID ="001", UserName="呵呵", Sex ="男" }); listUser.Add(new User { UserID = "002", UserName = "哈哈", Sex = "女" }); listUser.Add(new User { UserID = "003", UserName = "嘿嘿", Sex = "男" }); JsonResult jsonUser = new JsonResult(); jsonUser = Json(listUser); return jsonUser; }
上面介绍的两种方法能够解决我们给DataGrid赋值的问题,其中方法二里面除了将List集合转换成Json对象以外,我们还可以自己写一个方法将List转换成Json格式的字符串,这样也可以给DataGrid赋值。虽然我们能够赋值,但是这样做也有一些其他的问题,比如说怎么它的分页怎么实现,这就是我们下一期将要讲解的内容