开发者

Building an OrderBy expression using the name of a property

开发者 https://www.devze.com 2023-04-06 09:19 出处:网络
I\'m trying to support sorting via the WebGrid control in MVC3, which passes the name of a property on my model into my actions via a sort parameter.

I'm trying to support sorting via the WebGrid control in MVC3, which passes the name of a property on my model into my actions via a sort parameter.

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);
}

This code works when I try to sort my model by the Name property, which is of type string. However, if I try to sort by Id I receive the error Expression of type 'System.Int32' cannot be used for return type 'System.Object'.


you could use Expression.Convert to perform Boxing.

0

精彩评论

暂无评论...
验证码 换一张
取 消