gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : Custom Sorting

转载 作者:行者123 更新时间:2023-12-01 19:31:42 25 4
gpt4 key购买 nike

我正在尝试在我的小型 asp.net mvc 应用程序中实现自定义排序。嗯,有很多可用的插件。但这次我想自己做。

这是我的表格标题:

 <tr>
<th>
S.No.
</th>
<th>
@Html.ActionLink("UrlTitle", "Index", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc"? "Desc":"Asc"), SortBy = "UrlTitle" })
</th>
<th>
@Html.DisplayNameFor(model => model.Url)
</th>
<th>
@Html.DisplayNameFor(model => model.UrlDesc)
</th>

<th>
@Html.DisplayNameFor(model => model.tbl_Category.CategoryName)
</th>
</tr>

这就是操作:

public ActionResult Index(String SortOrder, String SortBy)
{
ViewBag.SortOrder = SortOrder;
ViewBag.SortBy = SortBy;

var model = ObjBs.GetAll().Where(x=>x.IsApproved == "A");
switch(SortOrder)
{
case "Asc":
model = model.OrderBy(x => x.UrlTitle);
break;
case "Desc":
model = model.OrderByDescending(x => x.UrlTitle);
break;
}
return View(model);
}

目前我可以按UrlTitle排序,没有问题。但是如果我也想按其他列排序,我写了这样的内容:

switch(SortBy)
{
case "UrlTitle":
switch(SortOrder)
{
case "Asc":
model = model.OrderBy(x => x.UrlTitle);
break;
case "Desc":
model = model.OrderByDescending(x => x.UrlTitle);
break;
default:
break;
}
break;

case "Category":
switch (SortOrder)
{
case "Asc":
model = model.OrderBy(x => x.UrlTitle);
break;
case "Desc":
model = model.OrderByDescending(x => x.UrlTitle);
break;
default:
break;
}
break;

case "URL":
switch (SortOrder)
{
case "Asc":
model = model.OrderBy(x => x.UrlTitle);
break;
case "Desc":
model = model.OrderByDescending(x => x.UrlTitle);
break;
default:
break;
}
break;

default:
break;
}

既然我可以通过参数传递列名,而不是编写嵌套开关,我不能做这样的事情吗:

    model = model.OrderBy(x => x.SortBy); Or, model = model.OrderBy(SortBy);

嗯,我认为当程序运行时,SortBy 的值将是columnName。但这似乎不起作用。

我只是不想重复写类似的代码。我怎样才能最大限度地减少它或使其变得更好?

最佳答案

如果你不想走反射路线,你应该可以使用 dynamic Linq供您查询。

关于asp.net-mvc - ASP.NET MVC : Custom Sorting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37246041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com