[英]Sorting with the Entity Framework in an ASP.NET MVC Application
i have this Index action method from which i am passing a result , and i want to sort my table through the same Index Action method how can i pass both the value to view. 我有传递结果的索引操作方法,并且我想通过相同的索引操作方法对表进行排序,如何将两个值都传递给视图。 here is my index Action method 这是我的索引操作方法
public ActionResult Index(string sortOrder)
{
var userCount = db.CountUser();
return View(userCount.ToList());
}
and here is my sorting code: 这是我的排序代码:
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
var teams = from t in db.Teams
select t;
switch (sortOrder)
{
case "name_desc":
teams = teams.OrderByDescending(t => t.TeamName);
break;
default:
teams = teams.OrderBy(t => t.TeamName);
break;
}
You can achieve that by: 您可以通过以下方法实现:
public ActionResult Index(string sortOrder)
{
var userCount = db.CountUser();
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : sortOrder;
var teams = from t in db.Teams
select t;
switch ((string)ViewBag.NameSortParm)
{
case "name_desc":
teams = teams.OrderByDescending(t => t.TeamName);
break;
default:
teams = teams.OrderBy(t => t.TeamName);
break;
}
ViewBag.Teams = teams.ToList();
return View(userCount.ToList());
}
And use ViewBag.Teams
in your view. 并在您的视图中使用ViewBag.Teams
。
However, proper solution for that I think would be creating a proper Model that contains both collections: 但是,我认为适当的解决方案是创建一个包含两个集合的适当模型:
public class MyIndexViewModel
{
public List<CountUser> CountUsers { get; set; }
public List<Team> Teams { get; set; }
}
public ActionResult Index(string sortOrder)
{
var userCount = db.CountUser();
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : sortOrder;
var teams = from t in db.Teams
select t;
switch ((string)ViewBag.NameSortParm)
{
case "name_desc":
teams = teams.OrderByDescending(t => t.TeamName);
break;
default:
teams = teams.OrderBy(t => t.TeamName);
break;
}
return View(new MyIndexViewModel { CountUsers = userCount.ToList(), Teams = teams.ToList() });
}
And also you need to change model type in your View to MyIndexViewModel
并且您还需要将View中的模型类型更改为MyIndexViewModel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.