2011-09-20 34 views
3

我試圖通過MVC3中的WebGrid控件進行排序,該控件通過參數sort將模型中屬性的名稱傳遞給我的動作。使用屬性的名稱構建OrderBy表達式

public class Agent { 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

[HttpGet] 
public ActionResult Index(string sort = "Id", string sortdir = "ASC") { 

    // Define the parameter that we are going to use in the OrderBy clause. 
    var param = Expression.Parameter(typeof(Agent), "agent"); 

    // Now we'll make our lambda function that returns the 
    // property's value by it's name. 
    var sortExpression = Expression.Lambda<Func<Agent, object>>(Expression.Property(param, sort), param); 

    var agents = entities.OrderBy(sortExpression).ToList(); 

    var model = new PagedResult<Agent> { 

     CurrentPage = 1, 
     PageCount = 1, 
     PageSize = DefaultPageSize, 
     Results = agents, 
     RowCount = agents.Count 

    }; 

    return View(model); 
} 

此代碼的工作,當我嘗試了Name屬性,它是string型的,以我的模型進行排序。不過,如果我嘗試Id排序我收到錯誤Expression of type 'System.Int32' cannot be used for return type 'System.Object'

+0

你嘗試使用Expression.Convert如下所示:http://stackoverflow.com/questions/2200209/expression-of-type-system-int32-cannot-be-used-for-return-type-system-對象/ 2200247#2200247 – Akhil

+0

我剛剛使用'Expression.TypeAs'工作。我不確定兩者之間有什麼區別,但是如果你想提交這個答案作爲回答,我將非常樂意給你信任。 –

+0

很高興你的問題解決了。我不確定兩者之間的區別是什麼! – Akhil

回答

2

你可以使用Expression.Convert進行拳擊。

相關問題