在ASP.net MVC3中排序数据列表时出现问题

时间:2011-07-13 10:47:45

标签: asp.net-mvc-3 entity-framework-4 repository entity

我正在尝试实现Asp.net MVC站点上的实体框架教程中显示的排序功能,这里

http://www.asp.net/entity-framework/tutorials/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

出于某种原因,虽然我可以看到正确的查询字符串被添加到网址,但数据没有排序,

我的控制器中有以下switch语句,允许我按客户名称或主要联系人姓名对数据进行排序

//Returns a list of all the customers to be displayed on the (Master edit page)
    //- TODO - Implement Paging Functionality
    public ViewResult Index(string sortOrder)
    {
        ViewBag.CustomerNameSortParm = String.IsNullOrEmpty(sortOrder) ? "CustomerName desc" : "";
        ViewBag.PrimaryContactNameSortParm = sortOrder == "PrimaryContactName" ? "PrimaryContactName desc" : "PrimaryContactName";
        var cust = repository.Customers;

        switch (sortOrder)
        {
            case "CustomerName desc":
                cust = repository.Customers.OrderByDescending(s => s.CustomerName);
                break;
            case "PrimaryContactName":
                cust = repository.Customers.OrderBy(s => s.PrimaryContactName);
                break;
            case "PrimaryContactName desc":
                cust = repository.Customers.OrderByDescending(s => s.PrimaryContactName);
                break;
            default:
                cust = repository.Customers.OrderBy(s => s.CustomerName);
                break;
        }

        return View(repository.Customers.ToList());
    }

然后在视图中我为每个政府标题创建了链接

<th class="header">
       @Html.ActionLink("Customer Name", "Index", new { sortOrder=ViewBag.CustomerNameSortParm })
    </th>
    <th class="header">
      @Html.ActionLink("Contact Name", "Index", new { sortOrder=ViewBag.PrimaryContactNameSortParm })
    </th>

当我点击链接时,我可以看到URL中的查询字符串值,如

http://localhost:58783/Admin/Index?sortOrder=PrimaryContactName

但数据没有排序,是否有人遇到类似问题,或者知道我哪里出错了?由于某种原因,实体框架教程底部的评论没有显示,所以我不知道是否有其他人有这个问题。

我可以在代码中看到的唯一区别是,在教程中,在控制器中使用了LINQ查询,我使用存储库并从存储库返回我的客户,该存储库返回一个IQueryable客户列表。

感谢任何建议。

小连

1 个答案:

答案 0 :(得分:2)

我认为您的退货声明是错误的,应该是 -

return View(cust.ToList());

而不是 -

return View(repository.Customers.ToList());

您似乎正在将数据排序到'cust'变量中,然后将未排序的集合返回到您的视图。