如何按记录动态排序

时间:2014-03-18 16:12:50

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我有以下索引操作方法,它显示对象列表如下: -

public ActionResult Index(string searchTerm = "", int page = 1)
        {
            string withOutSpace = searchTerm.Trim();
            ViewBag.searchTerm = searchTerm;
            int pagesize;
            bool succeed = int.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"], out pagesize);
            var racks = repository.AllFind(withOutSpace).OrderBy(a => a.Technology.SerialNumber).ToPagedList(page, pagesize);

目前我总是按SerialNumber排序,但我的问题是如何将参数传递给我的索引actionmethod并根据传递的参数执行OrderBy,例如价格,日期等。 谁有人建议? 第二个问题我怎么能第一次打电话给orberby升序而第二次打电话来做降序呢? 感谢

2 个答案:

答案 0 :(得分:3)

public ActionResult Index(string searchTerm = "", string sort, bool asc, int page = 1)
{
    string withOutSpace = searchTerm.Trim();
    ViewBag.searchTerm = searchTerm;
    int pagesize;
    bool succeed = int.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"], out pagesize);
    var racks = repository.AllFind(withOutSpace);

    if(asc)
    {
        switch(sort)
        {
            case "price":
                racks = racks.OrderBy(a => a.Technology.Price);
                break;
            case "date":
                racks = racks.OrderBy(a => a.Technology.Date);
                break;
            case default:
                racks = racks.OrderBy(a => a.Technology.SerialNumber);
                break;
        }
    }
    else
    {
        switch(sort)
        {
            case "price":
                racks = racks.OrderByDescending(a => a.Technology.Price);
                break;
            case "date":
                racks = racks.OrderByDescending(a => a.Technology.Date);
                break;
            case default:
                racks = racks.OrderByDescending(a => a.Technology.SerialNumber);
                break;
        }
    }
    racks = racks.ToPagedList(page, pagesize)

答案 1 :(得分:0)

你可以在orderBymethod中使用反射......比如

racks.OrderBy(a => { 
                        //use reflection get the property
                        PropInfo prop = a.GetType().GetProperty("price");
                        return prop;
                   })

我还没有测试过这段代码......这只是一个想法..