首页 > 代码库 > datagrid显示外键对象

datagrid显示外键对象

在显示数据列表时,会遇到外键的处理情况,比如,显示文章列表时,我们还要显示文章的分类,而文章分类在文章表中是以外键出现的。

1.View

<div style="width:100%;height:100%;">
    <table class="easyui-datagrid" id="datagridArtic" style="width: 100%; height: 95%;" data-options="singleSelect:true,url:‘@Url.Action("GetArticList")‘,method:‘get‘,toolbar:toolbar" pagination="true" sortname="Id" sortorder="asc">
        <thead>
            <tr>
                <th style="width:10%" data-options="field:‘Id‘" sortable="true">编号</th>
                <th style="width:20%" data-options="field:‘Title‘" sortable="true">标题</th>
                <th style="width:40%" data-options="field:‘Contents‘">内容</th>
                <th style="width:20%" data-options="field:‘Name‘, formatter: function(value,row,index){return new Object(row[‘ArticleGroup‘]).Name;}" sortable=" true">分组</th>
                <th style="width:10%" data-options="field:‘Views‘" sortable="true">浏览量</th>
            </tr>
        </thead>
    </table>
</div>

2.Controller

   [HttpGet]      

   public string GetArticList(int page, int rows, string sort, string order)    

   {         

      int total = articleService.GetList(x => x.IsDeleted == false).ToList().Count();  //数据总数         

      var list = articleService.GetQueryableList(x => x.IsDeleted == false);       

      var sortList = articleService.Sorting(list, sort, order);   //排序        

      var pageList = articleService.Paging(sortList, page, rows).ToList();   //分页                     

      Dictionary<string, object> data = http://www.mamicode.com/new Dictionary();

      data.Add("total", total);       

      data.Add("rows", pageList);

      JsonSerializerSettings settings = new JsonSerializerSettings();        

      settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;       

      var json = JsonConvert.SerializeObject(data, settings);           

      return json;      

   }

注:

1.分组名称 Name属性是row下两层的属性,正常情况下easyui是取不到第二层的数据的,只有用formatter才能取到。return后面的内容其实就相当于row.ArticleGroup.Name

2.由于EF读出的数据中,外键的引用具有循环性,比如 Atric对象有ArticGroup的外键引用,所以Atric有ArticGroup的属性,而ArticGroup下又有Artic的集合。 所以当JSon序列化时,如果不做处理,会抛出异常。处理:“settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; ”

datagrid显示外键对象