【发布时间】:2011-09-20 16:16:15
【问题描述】:
我正在尝试通过 MVC3 中的 WebGrid 控件支持排序,该控件通过 sort 参数将我模型上的属性名称传递到我的操作中。
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'。
【问题讨论】:
-
您是否尝试过使用 Expression.Convert,如下所示:stackoverflow.com/questions/2200209/…
-
我刚刚使用
Expression.TypeAs让它工作。我不确定这两者之间的区别是什么,但如果您想将其作为答案提交,我将非常乐意为您提供信用。 -
很高兴您的问题得到解决。我不确定两者之间的区别是什么!
标签: c# asp.net-mvc reflection expression-trees