在模型绑定的Listview中对外键列进行排序
我使用Listview来显示一些使用模型绑定的数据,并尝试对Listview中与数据源中的外键列(即book列)相关的列进行排序 数据模型如下:在模型绑定的Listview中对外键列进行排序,listview,sorting,model-binding,entity-framework-6,commandargument,Listview,Sorting,Model Binding,Entity Framework 6,Commandargument,我使用Listview来显示一些使用模型绑定的数据,并尝试对Listview中与数据源中的外键列(即book列)相关的列进行排序 数据模型如下: public class Book { public Book() { this.Factions = new HashSet<Faction>(); } public int Id { get; set; } [Required] [MaxLength(50)] publ
public class Book
{
public Book() {
this.Factions = new HashSet<Faction>();
}
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Title { get; set; }
public virtual ICollection<Faction> Factions { get; set; }
}
public class Faction
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(10)]
public string Abbreviation { get; set; }
public int? BookId { get; set; }
public virtual Book Book { get; set; }
}
公共课堂教材
{
公共书籍(){
this.派系=新HashSet();
}
公共int Id{get;set;}
[必需]
[MaxLength(50)]
公共字符串标题{get;set;}
公共虚拟ICollection派系{get;set;}
}
公共阶级派系
{
公共int Id{get;set;}
[必需]
[MaxLength(50)]
公共字符串名称{get;set;}
[MaxLength(10)]
公共字符串缩写{get;set;}
public int?BookId{get;set;}
公共虚拟图书{get;set;}
}
这是显示ListItem标题的HTML
<asp:ListView ID="FactionListView" runat="server"
ItemType="DCW.Models.Faction" DataKeyNames="Id"
SelectMethod="FactionGetData"
<LayoutTemplate>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>
<asp:LinkButton ID="FactionListViewName" runat="server" CommandName="Sort"
CommandArgument="Name">Name</asp:LinkButton></th>
<th>
<asp:LinkButton ID="FactionListViewAbbreviation" runat="server" CommandName="Sort"
CommandArgument="Abbreviation">Abbreviation</asp:LinkButton></th>
<th>
<asp:LinkButton ID="FactionListViewBook" runat="server" CommandName="Sort"
CommandArgument="Book">Book</asp:LinkButton></th>
</tr>
</thead>
<tbody>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</tbody>
</table>
</LayoutTemplate>
因此,模型绑定似乎无法处理开箱即用的导航属性(外键)排序。我发现以下是我用来解决这个问题的方法:
因此:
<asp:LinkButton ID="FactionListViewBook" runat="server" CommandName="Sort"
CommandArgument="Book">Book</asp:LinkButton></th>
<asp:LinkButton ID="FactionListViewBook" runat="server" CommandName="Sort"
CommandArgument="Book.Title">Book</asp:LinkButton></th>
public IQueryable<GameFaction> FactionGetData(string sortByExpression)
{
IQueryable<Faction> query = _context.Factions.Include(faction => faction.Book);
sortByExpression = sortByExpression == null ? "Name" : sortByExpression;
if (sortByExpression.EndsWith(" DESC"))
{
query = query.OrderByDescending(sortByExpression.SubString(0, sortByExpression.Length - 5));
}
else
{
query = query.OrderBy(sortByExpression);
}
return query;
}