我有一个存储在数据库中的可能条目列表。我根据放入文本框的条目或单击html动作链接,将这些条目排序并显示到新视图中。这个的主要思想可以在下面看到。
public ActionResult Index(string sortOrder, string searchString, int? sortType)
{
if (!String.IsNullOrEmpty(searchString))
{
if (sortType == 1)
{
//Sort the results strictly based on the HTML header options
applications = applications.Where(s => s.Business.Equals(searchString));
}
else
{
//sort based on the input of the form
applications = applications.Where(s => s.Business.Contains(searchString)
|| s.ApName.Contains(searchString));
}
}
return View(applications.ToList());
}
通过单击类似的链接
激活此if语句的第一部分<li>@Html.ActionLink("CITY", "index", "app", new {SearchString = "city", sortType=1}, null)</li>
虽然我的代码正在运行,但我只是想知道是否有更“正确”的方式来执行我编码的内容,而无需传递sortType变量来确定是否基于表单或actionlink进行排序。我确信我所做的事情是非常糟糕的做法,但我对此很新。
答案 0 :(得分:0)
我不确定这是不是你所追求的因为你的问题一直在谈论排序,但你的代码正在谈论过滤。您可以尝试指定默认值,以便在未填充这些条件时Where语句短路。例如:
public ActionResult Index(string city = null, string business = null){
var model = applications
.Where(x => city == null || x.City.Contains(city))
.Where(x => business == null || x.Business == business);
return View(model);
}