3

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'.

Justin Rusbatch
  • 3,992
  • 2
  • 25
  • 43
  • have you tried using Expression.Convert as shown here: http://stackoverflow.com/questions/2200209/expression-of-type-system-int32-cannot-be-used-for-return-type-system-object/2200247#2200247 – Akhil Sep 20 '11 at 16:27
  • I just got it working using `Expression.TypeAs`. I'm not sure what the difference between the two is yet, but if you want to submit that as an answer I'll be more than happy to give you credit. – Justin Rusbatch Sep 20 '11 at 16:34
  • glad your issue is solved. Am not sure either as to whats the difference between the two is! – Akhil Sep 20 '11 at 16:54

1 Answers1

2

you could use Expression.Convert to perform Boxing.

Akhil
  • 7,570
  • 1
  • 24
  • 23