我已对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 进行排序。之后,如果我点击个人号码,它将按它排序。我该如何改进?
答案 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 == null
和swith
阻止将转到default
个案例。
TLDR
您将每次第二次获得default switch
个案例。
要解决您的问题,请执行以下操作:
ViewBag.NameSortParm = "fname";
ViewBag.lastNameSortParm = "lastName";
ViewBag.idNumberSortParm = "idNumber";
或使用不同的排序参数创建枚举或实现排序策略模式或其他。