通过actionlink对表中的项进行排序

时间:2015-03-27 07:21:39

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我已对this article

中的项目进行了排序

这是我的控制器:

ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "fname" : "";
            ViewBag.lastNameSortParm = String.IsNullOrEmpty(sortOrder) ? "lastName" : "";
            ViewBag.idNumberSortParm = String.IsNullOrEmpty(sortOrder) ? "idNumber" : "";
 var persons = from s in db.PRT_PARTNERS
                          select s;
            switch (sortOrder)
            {
                case "fname_desc":
                    persons = persons.OrderBy(s => s.FIRST_NAME);
                    break;
                case "lastName_desc":
                    persons = persons.OrderBy(s => s.LAST_NAME);
                    break;
                case "idNumber_desc":
                    persons = persons.OrderBy(s => s.PERSONAL_NUMBER);
                    break;
default:
                    persons = persons.OrderBy(s => s.FIRST_NAME);
                    break;
            }

以下是观点:

 <th>
            @Html.ActionLink("სახელი", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
        <th>
            @Html.ActionLink("გვარი", "Index", new { sortOrder = ViewBag.lastNameSortParm })
        </th>
        <th>
            @Html.ActionLink("პირადი ნომერი", "Index", new { sortOrder = ViewBag.idNumberSortParm })
        </th>

但这是一个问题。如果我点击lastName,则按姓氏排序,但如果我点击个人号码,则会使用 FIRSTNAME 而不是 personalnumber 进行排序。之后,如果我点击个人号码,它将按它排序。我该如何改进?

1 个答案:

答案 0 :(得分:1)

你的逻辑很糟糕。 问题在于此代码:

ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "fname" : "";
ViewBag.lastNameSortParm = String.IsNullOrEmpty(sortOrder) ? "lastName" : "";
ViewBag.idNumberSortParm = String.IsNullOrEmpty(sortOrder) ? "idNumber" : "";
控制器的

HttpGet方法以sortOrder == null(我推测)开头,您的所有ViewBag项都会获得一些价值"fname", "lastName""idNumber"。在switch阻止之后转到default个案,因为sortOrder == null

但是当您从sortOrder视图中获得某个值的答案时,由于ViewBag,您的sortOrder != null项将变为空:

String.IsNullOrEmpty(sortOrder) ? "idNumber" : ""; 
\\if sortOrder is not null or empty it will be empty anyway.

switch阻止一次正常后,您的视图将返回sortOrder==null,因为您的所有ViewBag.Items == nullswith阻止将转到default个案例。

TLDR 您将每次第二次获得default switch个案例。

要解决您的问题,请执行以下操作:

ViewBag.NameSortParm = "fname";
ViewBag.lastNameSortParm = "lastName";
ViewBag.idNumberSortParm = "idNumber";

或使用不同的排序参数创建枚举或实现排序策略模式或其他。