2014-11-04 14 views
1

我使用jQuery的數據表和擴展我做了multicolum排序讀那些帖子:數據表multisort列.NET MVC提示

我的問題是,那些兩種方法都依賴於我在我的控制器中使用的模型,在這種情況下,

如果我需要在oth中使用類似的代碼例如,我需要複製它並改變模型字段和類型。

這在我看來不是很乾。

如何繼續?控制者是這兩種方法的好位置嗎?

private IOrderedQueryable<User> CreateSortedQuery(DataTableParameterModel parameterModel, IQueryable<User> baseQuery) 
{ 
    var orderedQuery = (IOrderedQueryable<User>)baseQuery; 

    for (int i = 0; i < parameterModel.iSortingCols; ++i) 
    { 
     var ascending = string.Equals("asc", parameterModel.sSortDir[i], StringComparison.OrdinalIgnoreCase); 
     int sortCol = parameterModel.iSortCol[i]; 

     Expression<Func<User, string>> orderByExpression = GetOrderingFunc(sortCol); 
     if (orderByExpression != null) 
     { 
      if (ascending) 
      { 
       orderedQuery = (i == 0) 
        ? orderedQuery.OrderBy(orderByExpression) 
        : orderedQuery.ThenBy(orderByExpression); 
      } 
      else 
      { 
       orderedQuery = (i == 0) 
        ? orderedQuery.OrderByDescending(orderByExpression) 
        : orderedQuery.ThenByDescending(orderByExpression); 
      } 
     } 
     else 
     { 
      if (ascending) 
      { 
       orderedQuery = (i == 0) 
        ? orderedQuery.OrderBy(c => c.Id) 
        : orderedQuery.ThenBy(c => c.Id); 
      } 
      else 
      { 
       orderedQuery = (i == 0) 
        ? orderedQuery.OrderByDescending(c => c.Id) 
        : orderedQuery.ThenByDescending(orderByExpression); 
      } 
     } 

    } 
    return orderedQuery; 
} 


private Expression<Func<User, string>> GetOrderingFunc(int ColumnIndex) 
{ 
    Expression<Func<User, string>> InitialorderingFunction; 
    switch (ColumnIndex) 
    { 
     case 1: 
      InitialorderingFunction = c => c.FirstName; 
      break; 
     case 2: 
      InitialorderingFunction = c => c.LastName; 
      break; 
     case 3: 
      InitialorderingFunction = c => c.UserName; 
      break; 
     case 4: 
      InitialorderingFunction = c => c.Email; 
      break; 
     case 5: 
      InitialorderingFunction = c => c.BusinessName; 
      break; 
     default: 
      InitialorderingFunction = null; 
      break; 
    } 

    return InitialorderingFunction; 
} 
+0

檢查這個答案http://stackoverflow.com/questions/26699105/library-for-jquery-datatables-asp-net-mvc – py3r3str 2014-11-04 16:16:42

+0

移動這些解決方案,感謝您的評論,我到達類似的解決方案http: //stackoverflow.com/questions/26759416/generics-c-sharp-organization-of-methods-that-depends-on-type – andrea 2014-11-05 14:18:51

回答

0

我想,你的問題是相當接近這兩個答案:

Property name evaluating from expression

public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class 
{ 
    var expression = (MemberExpression)action.Body; 
    string fieldName = expression.Member.Name; 

Applying linq sorting passing string values與LINQ動態查詢庫:

var result = data 
    .Where(/* ... */) 
    .Select(/* ... */) 
    .OrderBy(fieldName + " asc");