EasyUI 之 DataGrid的两种赋值步骤
EasyUI 之 DataGrid的两种赋值方法
上一篇博客《EasyUI 之 DataGrid分页组件中文显示的两种方法》中我们使用EasyUI-DataGrid在前台添加了一个表格,并且让表格的分页控件显示为中文。现在我们有了DataGrid,我们怎么让它显示我们想要的数据呢?今天就跟大家聊一聊在MVC中怎么给DataGrid传值。
方法一:使用ViewData赋值
然后,我们在Action中添加假数据,并将假数据放到ViewData中
最后,我们在前台用ViewData给DataGrid赋值

方法二:使用url赋值
首先,我们在前台的DataGrid中加上URL属性
然后,我们在相应的控制器中添加一个得到json数据的方法

上一篇博客《EasyUI 之 DataGrid分页组件中文显示的两种方法》中我们使用EasyUI-DataGrid在前台添加了一个表格,并且让表格的分页控件显示为中文。现在我们有了DataGrid,我们怎么让它显示我们想要的数据呢?今天就跟大家聊一聊在MVC中怎么给DataGrid传值。
方法一:使用ViewData赋值
首先,我们创建一个User的实体类
public class User { public string UserID; public string UserName; public string Sex; }
然后,我们在Action中添加假数据,并将假数据放到ViewData中
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(); }
最后,我们在前台用ViewData给DataGrid赋值
<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>
方法二:使用url赋值
首先,我们在前台的DataGrid中加上URL属性
<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>
然后,我们在相应的控制器中添加一个得到json数据的方法
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赋值。虽然我们能够赋值,但是这样做也有一些其他的问题,比如说怎么它的分页怎么实现,这就是我们下一期将要讲解的内容