Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 在asp.net MVC中对表进行排序_Asp.net Mvc_Sorting_Html Table - Fatal编程技术网

Asp.net mvc 在asp.net MVC中对表进行排序

Asp.net mvc 在asp.net MVC中对表进行排序,asp.net-mvc,sorting,html-table,Asp.net Mvc,Sorting,Html Table,我想知道人们是如何在asp.net mvc中对表进行排序的? 我听说过javascript解决方案可以很好地处理非分页表,比如jquery的表分类器,但我需要一个能够处理分页表的解决方案 我正在做的项目目前使用以下解决方案,但我发现它非常混乱 控制器 public ActionResult Sort(string parameter) { IEnumerable<IProduct> list; if (Session["Model"] != null) list =

我想知道人们是如何在asp.net mvc中对表进行排序的? 我听说过javascript解决方案可以很好地处理非分页表,比如jquery的表分类器,但我需要一个能够处理分页表的解决方案

我正在做的项目目前使用以下解决方案,但我发现它非常混乱

控制器

public ActionResult Sort(string parameter)
{  

 IEnumerable<IProduct> list;

 if (Session["Model"] != null)
  list = (IEnumerable<IProduct>)Session["Model"]).ToList<IProduct>();
 else
  list = _service.GetAll();

 if (Session["parameter"] == null && Session["sortDirection"] == null)
 {
  //set the parameter and set the sort to desc
  Session["parameter"] = parameter;
  Session["sortDirection"] = "DESC";
 }
 else if (Session["parameter"] != null) //already set so not the first time
 {
  //same parameter sent
  if (Session["parameter"].ToString().Equals(parameter))
  {
   //check sort direction and reverse
   if (Session["sortDirection"].ToString().Equals("DESC"))
    Session["sortDirection"] = "ASC";
   else
    Session["sortDirection"] = "DESC";
  }
  else //different parameter sent
  {
   Session["sortDirection"] = "DESC";
   Session["parameter"] = parameter;
  }
 }

 if (Session["sortDirection"].CompareTo("ASC") == 0)
  list = Models.ContollerHelpers.SortingHelper.OrderBy(list.AsQueryable(), column);
 else
  list = Models.ContollerHelpers.SortingHelper.OrderByDescending(list.AsQueryable(), column);

 return View("Results", list.ToList);
}
public class Helper()
{
 private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
 {
  ParameterExpression param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming
  MemberExpression property = Expression.PropertyOrField(param, propertyName);
  LambdaExpression sort = Expression.Lambda(property, param);

  MethodCallExpression call = Expression.Call(
   typeof(Queryable),
   (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
   new[] { typeof(T), property.Type },
   source.Expression,
   Expression.Quote(sort));

  return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
 }

 public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, false, false);
 }

 public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, true, false);
 }

 public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, false, true);
 }

 public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, true, true);
 }
}
public ActionResult排序(字符串参数)
{  
i可数列表;
如果(会话[“模型”]!=null)
list=(IEnumerable)会话[“Model”]).ToList();
其他的
list=_service.GetAll();
if(会话[“参数”]==null&&Session[“sortDirection”]==null)
{
//设置参数并将排序设置为desc
会话[“参数”]=参数;
会话[“sortDirection”]=“DESC”;
}
else if(Session[“parameter”]!=null)//已设置,因此不是第一次
{
//发送相同的参数
if(会话[“参数”].ToString()等于(参数))
{
//检查分拣方向和反向
if(Session[“sortDirection”].ToString()等于(“DESC”))
会话[“sortDirection”]=“ASC”;
其他的
会话[“sortDirection”]=“DESC”;
}
else//发送了不同的参数
{
会话[“sortDirection”]=“DESC”;
会话[“参数”]=参数;
}
}
如果(会话[“排序方向”]。比较(“ASC”)==0)
list=Models.ContollerHelpers.SortingHelper.OrderBy(list.AsQueryable(),column);
其他的
list=Models.ContollerHelpers.SortingHelper.OrderByDescending(list.AsQueryable(),column);
返回视图(“结果”,list.ToList);
}
助手

public ActionResult Sort(string parameter)
{  

 IEnumerable<IProduct> list;

 if (Session["Model"] != null)
  list = (IEnumerable<IProduct>)Session["Model"]).ToList<IProduct>();
 else
  list = _service.GetAll();

 if (Session["parameter"] == null && Session["sortDirection"] == null)
 {
  //set the parameter and set the sort to desc
  Session["parameter"] = parameter;
  Session["sortDirection"] = "DESC";
 }
 else if (Session["parameter"] != null) //already set so not the first time
 {
  //same parameter sent
  if (Session["parameter"].ToString().Equals(parameter))
  {
   //check sort direction and reverse
   if (Session["sortDirection"].ToString().Equals("DESC"))
    Session["sortDirection"] = "ASC";
   else
    Session["sortDirection"] = "DESC";
  }
  else //different parameter sent
  {
   Session["sortDirection"] = "DESC";
   Session["parameter"] = parameter;
  }
 }

 if (Session["sortDirection"].CompareTo("ASC") == 0)
  list = Models.ContollerHelpers.SortingHelper.OrderBy(list.AsQueryable(), column);
 else
  list = Models.ContollerHelpers.SortingHelper.OrderByDescending(list.AsQueryable(), column);

 return View("Results", list.ToList);
}
public class Helper()
{
 private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
 {
  ParameterExpression param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming
  MemberExpression property = Expression.PropertyOrField(param, propertyName);
  LambdaExpression sort = Expression.Lambda(property, param);

  MethodCallExpression call = Expression.Call(
   typeof(Queryable),
   (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
   new[] { typeof(T), property.Type },
   source.Expression,
   Expression.Quote(sort));

  return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
 }

 public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, false, false);
 }

 public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, true, false);
 }

 public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, false, true);
 }

 public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string propertyName)
 {
  return OrderingHelper(source, propertyName, true, true);
 }
}
public类助手()
{
私有静态IOrderedQueryable OrderingHelper(IQueryable源、字符串属性名称、布尔降序、布尔其他级别)
{
ParameterExpression param=Expression.Parameter(typeof(T),string.Empty);//我不关心一些命名
MemberExpression属性=Expression.PropertyOrField(参数,propertyName);
LambdaExpression sort=Expression.Lambda(属性,参数);
MethodCallExpression调用=表达式.call(
类型(可查询),
(!anotherLevel?“OrderBy”:“ThenBy”)+(降序?“降序”:string.Empty),
新[]{typeof(T),property.Type},
来源.表达式,
Expression.Quote(sort));
返回(IOrderedQueryable)source.Provider.CreateQuery(调用);
}
公共静态IOrderedQueryable OrderBy(此IQueryable源,字符串propertyName)
{
return OrderingHelper(source,propertyName,false,false);
}
公共静态IOrderedQueryable OrderByDescending(此IQueryable源,字符串propertyName)
{
return OrderingHelper(source,propertyName,true,false);
}
公共静态IOrderedQueryable ThenBy(此IOrderedQueryable源,字符串propertyName)
{
return OrderingHelper(source,propertyName,false,true);
}
公共静态IOrderedQueryable然后按降序(此IOrderedQueryable源,字符串propertyName)
{
return OrderingHelper(source,propertyName,true,true);
}
}
列表视图

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Models.Interface.IProduct>>" %>
<% Session["model"] = Model; %>
 <table>
    <tr>
   <th>
    Edit Details
   </th>
   <th>
    <%=Html.ActionLink("Id","Sort",new {parameter ="Id"}) %>
   </th>
   <th>
    <%=Html.ActionLink("Name", "Sort", new { parameter = "Name"})%>
   </th>
   <th>
    <%=Html.ActionLink("Status", "Sort", new { parameter = "Status" })%>
   </th>
   <th>
    <%=Html.ActionLink("Notes", "Sort", new { parameter = "Notes"})%>
   </th>
  </tr>
  <% foreach (var item in Model){ %>

   <tr>
    <td>
     <%= Html.ActionLink("Edit", "Edit", new {  id=item.Id }) %> |
    </td>
    <td>
     <%= Html.Encode(item.Id) %>
    </td>
    <td>
     <%= Html.Encode(item.Name) %>
    </td>
    <td>
     <%= Html.Encode(item.Status) %>
    </td>
    <td>
     <%= Html.Encode(item.Notes) %>
    </td> 
   </tr>

  <% } %>   
    </table>

编辑详细信息
|
这是做这种事情的唯一方法吗?
如果有人知道一种更好的方法,不需要将所有记录一次加载到一个页面,那么请链接到示例。

我更喜欢这里描述的方法:

例如:

var products = new List<Products>();
products = ProductRepository.GetAll();

// Sort Results
products.Sort(
    delegate(Products p1, Products p2) {
    return p1.Name.CompareTo(p2.Name);
});
var产品=新列表();
products=ProductRepository.GetAll();
//排序结果
产品。分类(
代表(产品p1、产品p2){
返回p1.Name.CompareTo(p2.Name);
});

查看数据表@这将使您可以通过简单的设置对结果进行分页和查询。它可以很好地处理ajax和json数据。看看这些样品。希望这对您有所帮助。

尝试以下扩展方法(从头开始):

静态类OrderByExtender
{
公共静态IOrderedEnumerable OrderBy(此IEnumerable集合、字符串键、字符串方向)
{
LambdaExpression sortLambda=BuildLambda(键);
if(direction.ToUpper()=“ASC”)
返回collection.OrderBy((Func)sortLambda.Compile());
其他的
返回collection.OrderByDescending((Func)sortLambda.Compile());
}
公共静态IOrderedEnumerable ThenBy(此IOrderedEnumerable集合、字符串键、字符串方向)
{
LambdaExpression sortLambda=BuildLambda(键);
if(direction.ToUpper()=“ASC”)
返回collection.ThenBy((Func)sortLambda.Compile());
其他的
返回集合。然后按降序((Func)sortLambda.Compile());
}
私有静态LambdaExpression BuildLambda(字符串键)
{
ParameterExpression TParameterExpression=表达式参数(类型为(T),“p”);
LambdaExpression sortLambda=Expression.Lambda(Expression.Convert(Expression.Property(TParameterExpression,key)、typeof(object))、TParameterExpression);
返回索特拉姆达;
}
}
用法:

var products = Session["Model"] as IEnumerable<Product>() ?? _service.GetAll();

return products.OrderBy("Name", "ASC").ThenBy("Price", "DESC");
var products=Session[“Model”]作为IEnumerable()_service.GetAll();
退货产品。订购人(“名称”、“ASC”)。然后订购人(“价格”、“说明”);
假设您一次仅使用1个orderby条件,则可以使用:

var products = Session["Model"] as IEnumerable<Product>();

var sortDirection = Session["Direction"] as string ?? "DESC";
Session["Direction"] = sortDirection == "DESC" ? "ASC" : "DESC";
sortDirection = Session["Direction"] as string;

return products.OrderBy(parameter, sortDirection);
var products=Session[“Model”]作为IEnumerable();
var sortDirection=Session[“Direction”]作为字符串??“描述”;
会话[“方向”]=排序方向==“描述”?“ASC”:“描述”;
sortDirection=会话[“方向”]作为字符串;
退货产品。订购人(参数,排序方向);

如果禁用JavaScript,则会出现问题

我会选择一个noscript解决方案

我有两个单选按钮组:

direction:  ( ) ascending    (.) descending

orderBy:  (.) Id   ( ) Name   ( ) Status
我将视图视为带有多个提交按钮的表单

(不带JavaScript)~~两个按钮的名称相同

在.aspx页面上,添加三个按钮:

 <input type="submit"    value="Requery"   name="submitButton"/>
 <input type="submit"    value="Previous"  name="submitButton"/>
 <input type="submit"    value="Next"      name="submitButton"/>
:做这件事的方法不止一种
<th>Date <a class="clickable" href="<%=Url.Action("SortStationVisits", New With {.SortField = "PlanningDate"})%>"><span class="colSort" style="display: inline-table;"></span></a></th>
Imports System.Linq.Expressions

Public Function OrderBy(Of T)(collection As IEnumerable(Of T), key As String, isDescending As Boolean) As IOrderedEnumerable(Of T)
    Dim sortLambda As LambdaExpression = BuildLambda(Of T)(key)
    If isDescending Then
        Return collection.OrderByDescending(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
    Else
        Return collection.OrderBy(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
    End If
End Function

Public Function ThenBy(Of T)(collection As IOrderedEnumerable(Of T), key As String, isDescending As Boolean) As IOrderedEnumerable(Of T)
    Dim sortLambda As LambdaExpression = BuildLambda(Of T)(key)

    If (isDescending) Then
        Return collection.ThenByDescending(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
    Else
        Return collection.ThenBy(DirectCast(sortLambda.Compile(), Func(Of T, Object)))
    End If
End Function

Private Function BuildLambda(Of T)(key As String) As LambdaExpression
    Dim TParameterExpression As ParameterExpression = Expression.Parameter(GetType(T), "p")
    Dim sortLambda As LambdaExpression = Expression.Lambda(Expression.Convert(Expression.[Property](TParameterExpression, key), GetType(Object)), TParameterExpression)
    Return sortLambda
End Function
Public Function SortStationVisits(Optional page As Integer = 1, Optional SortField As String = "") As ActionResult
    Dim sps = LoadSession()

    If SortField = sps.StationVisitSorter Then
        sps.StationVisitDescOrder = Not (sps.StationVisitDescOrder)
    Else
        sps.StationVisitDescOrder = False
    End If

    sps.StationVisitSorter = SortField

    SaveSession(sps)
    Return RedirectToAction("Show")
End Function
spv.SelectableStationVisits = spv.SelectableStationVisits.OrderBy(sps.StationVisitSorter, sps.StationVisitDescOrder).ToList