0

我使用ListView來顯示一些使用模型綁定的數據,並且我試圖在列表視圖中對與數據源中的外鍵列相關的列進行排序,即書籍欄。在模型綁定列表視圖中排序外鍵列

數據模型如下:

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; } 
} 

這是爲列表項

<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> 

顯示標題當書LinkBut​​ton的點擊,我得到了錯誤的HTML:SYS。 WebForms.PageRequestManagerServerErrorException:DbSortClause表達式必須具有可比較的類型。

如果我將Linkbutton CommandArgument更改爲Book.Id或it.Book.Title(我已閱讀了其他一些帖子可能會發揮作用),那麼我得到以下錯誤:Sys.WebForms.PageRequestManagerServerErrorException:異常已被拋出調用的目標。

那麼如何排序模型綁定列表視圖的相關列?

謝謝。

回答

0

所以看起來,模型綁定不處理排序導航屬性(外鍵)開箱即用。我發現下面的這是我用來解決這個問題: ASP.Net 4.5 Model Binding Sorting By Navigation Property

所以這樣的:

<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> 

而且我SelectMethod變成了:

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; 
    } 

請注意,這使用了第四節中提到的擴展方法e鏈接上面最初來自這裏: Dynamic LINQ OrderBy on IEnumerable<T>