方法一:使用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賦值。雖然我們能夠賦值,但是這樣做也有一些其他的問題,比如說怎么它的分頁怎么實現,這就是下一節將要講解的內容
