https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-applicationpublic ActionResult Index(string sortOrder){ ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; var students = from s in db.Students select s; switch (sortOrder) { case "name_desc": students = students.OrderByDescending(s => s.LastName); break; case "Date": students = students.OrderBy(s => s.EnrollmentDate); break; case "date_desc": students = students.OrderByDescending(s => s.EnrollmentDate); break; default: students = students.OrderBy(s => s.LastName); break; } return View(students.ToList());}三元運(yùn)算符僅根據(jù)條件返回結(jié)果之一,它們不會(huì)更改 sortOrder 對(duì)嗎?如果 sortOrder 是“Date”,那么代碼將設(shè)置ViewBag.DateSortParm 為“date_desc”,但 sortOrder 不是仍然是“Date”,所以它實(shí)際上不會(huì)改變順序?我看不出這段代碼如何正常工作,但確實(shí)如此。
1 回答

HUX布斯
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
1)三元運(yùn)算符只需設(shè)置一個(gè) ViewBag 值,是的。它們不會(huì)改變sortOrder
變量的內(nèi)容。事實(shí)上恰恰相反——他們根據(jù).sortOrder
students
2)你是對(duì)的,它對(duì)實(shí)際排序的方式?jīng)]有任何影響,這是由switch
語句確定的。
ViewBag 參數(shù)值設(shè)置為與您預(yù)期相反的原因是因?yàn)樵谝晥D中它們用于構(gòu)建超鏈接,當(dāng)單擊這些超鏈接時(shí),將導(dǎo)致數(shù)據(jù)以與現(xiàn)在相反的方式排序。例如,如果當(dāng)前對(duì)“Date”(日期升序)進(jìn)行排序,那么它將構(gòu)建一個(gè)鏈接,如果單擊該鏈接,則會(huì)向服務(wù)器傳回一條指令以重新排序并返回?cái)?shù)據(jù),但這次按“date_desc”排序(Date降序)代替。因此,如果您考慮到這些值稍后用于什么,它確實(shí)是有道理的。
- 1 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報(bào)
0/150
提交
取消