ASP.Net 4.5模型绑定按导航属性排序

本文关键字:导航 属性 排序 绑定 模型 Net ASP | 更新日期: 2023-09-27 18:13:48

全部,

我有一个网格视图,它包含以下列。分页很好,但排序不好。每次我点击"类别"列按类别排序时,我都会收到以下错误:

没有为类型"ESA.Data.Models.Entity.Project"定义实例属性"Category.CategoryName">

此错误语句不正确,因为gridview能够正确显示列。

以下是的选择方法

    public IQueryable<Project> getProjects()
    {
        ApplicationServices objServices = new ApplicationServices();
        IQueryable<Project> lstProject;
        lstProject = objServices.getProjects();
        return lstProject;
    }

有什么建议吗?

    <asp:GridView ID="grdProject" runat="server" ShowHeader="true" 
        AutoGenerateColumns="false" CellPadding="2" CellSpacing="2" 
        ItemType="ESA.Data.Models.Entity.Project"
        SelectMethod="getProjects"
        DataKeyNames="ProjectID" 
        AllowSorting="true"
        AllowPaging="true"
        PageSize="5">
        <Columns>
            <asp:BoundField DataField="ProjectID" HeaderText="ID " ItemStyle-Width="10" />
            <asp:BoundField DataField="Category.CategoryName" HeaderText="Category" SortExpression="Category.CategoryName" />
            <asp:BoundField DataField="ProjectName" HeaderText="Project Name" ItemStyle-Width="300"  />
            <asp:BoundField DataField="Status.StatusName" HeaderText="Status" SortExpression="Status.StatusName"  />
            <asp:BoundField DataField="AddedByUser.UserName" HeaderText="Added By" ItemStyle-Width="120"  />
            <asp:BoundField DataField="AddedDate" HeaderText="Added Date" ItemStyle-Width="90" DataFormatString="{0:d}"  />
        </Columns>
    </asp:GridView>

ASP.Net 4.5模型绑定按导航属性排序

我在Listview控件中遇到了类似的问题。我就这样解决了。

首先,我在IEnumerable<T>

在Listview的"OnSorting"事件中,我添加了以下代码。

protected void lv_Sorting(object sender, ListViewSortEventArgs e)
{
    e.Cancel = true;
    ViewState["OrderBy"] = e.SortExpression;
    lvList.DataBind();
}

我添加了一种相当标准的方式来捕获这个的分拣方向列表

public SortDirection sortDirection
{
    get
    {
        if (ViewState["sortdirection"] == null)
        {
            ViewState["sortdirection"] = SortDirection.Ascending;
            return SortDirection.Ascending;
        }
        else if ((SortDirection)ViewState["sortdirection"] == SortDirection.Ascending)
        {
            ViewState["sortdirection"] = SortDirection.Descending;
            return SortDirection.Descending;
        }
        else
        {
            ViewState["sortdirection"] = SortDirection.Ascending;
            return SortDirection.Ascending;
        }
    }
    set
    {
        ViewState["sortdirection"] = value;
    }
}

在我的Listview中,Selectmethod看起来像这样(使用Marc的扩展方法(

public IQueryable<SomeObject> GetObjects([ViewState("OrderBy")]String OrderBy = null)
{
    var list = GETSOMEOBJECTS();
    if (OrderBy != null)
    {
        switch (sortDirection)
        {
            case SortDirection.Ascending:
                list = list.OrderByDescending(OrderBy);
                break;
            case SortDirection.Descending:
                list = list.OrderBy(OrderBy);
                break;
            default:
                list = list.OrderByDescending(OrderBy);
                break;
        }
    }
    return list;
}

我还没有在GridView中尝试过,但我很确定它也能正常工作。

编辑下面是一个linq扩展类的例子,它应该可以在中工作

public static class LinqExtensions
{
    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "OrderBy");
    }
    public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "OrderByDescending");
    }
    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "ThenBy");
    }
    public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "ThenByDescending");
    }
    static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
    {
        string[] props = property.Split('.');
        Type type = typeof(T);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;
        foreach (string prop in props)
        {
            // use reflection (not ComponentModel) to mirror LINQ
            PropertyInfo pi = type.GetProperty(prop);
            expr = Expression.Property(expr, pi);
            type = pi.PropertyType;
        }
        Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
        LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
        object result = typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName
                        && method.IsGenericMethodDefinition
                        && method.GetGenericArguments().Length == 2
                        && method.GetParameters().Length == 2)
                .MakeGenericMethod(typeof(T), type)
                .Invoke(null, new object[] { source, lambda });
        return (IOrderedQueryable<T>)result;
    } 
}

只需在页面上添加一个使用"whatevernamespaceyouused",你就可以开始了。

将名为sortByExpression的字符串参数添加到getProjects()方法中。

如果gridView在你的方法签名中找到了这个参数,它不会试图"自动排序"你的结果,它会让你完成这项工作。

要自己完成这项工作,可以使用DynamicLinq(可以添加nuget包,也可以使用Drauka发布的LinqExtensions类(。

所以你的方法看起来是这样的:

// using System.Linq.Dynamic;
public IQueryable<Project> getProjects(string sortByExpression)
{
    ApplicationServices objServices = new ApplicationServices();
    IQueryable<Project> lstProject = objServices.getProjects();
    if (!String.IsNullOrEmpty(sortByExpression))
        lstProject = lstProject.OrderBy(sortByExpression);
    return lstProject;
}

这样就不会绕过gridView排序样式。

源:反编译的框架代码,特别是System.Web.UI.WebControls.ModelDataSourceView.IsAutoSortingRequired(...)

Drauka您的解决方案对我有效,但如果我已经引用了System.Linq.Dynamic ,我会在这行代码中出错

给我语法错误的两行是

lstProject=lstProject.OrderByDescending(OrderBy(;

并且错误消息是

无法根据用法推断方法"System.Linq.Enumerable.OrderByDescending(System.Collections.Generic.IEnumerable,System.Func("的类型参数。请尝试显式指定类型参数。

    public IQueryable<Project> getProjects([ViewState("OrderBy")]String OrderBy = null)
    {
        ApplicationServices objServices = new ApplicationServices();
        var lstProject = objServices.getProjects();
        if (OrderBy != null)
        {
            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    lstProject = lstProject.OrderByDescending(OrderBy);
                    break;
                case SortDirection.Descending:
                    lstProject = lstProject.OrderBy(OrderBy);
                    break;
                default:
                    lstProject = lstProject.OrderByDescending(OrderBy);
                    break;
            }
        }
        return lstProject;
    }