John John
John John

Reputation: 1

How to dynamically order by the records

I have the following index action method which display a list of objects as follow:-

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

currently I am always ordering by the SerialNumber, but my question is how I can pass a parameter to my index actionmethod and do the OrderBy based on the passed parameter, such as price, date, etc. can anyone advice? And second question how I can make the first call to orberby ascending while the second call to do the order descending ? Thanks

Upvotes: 0

Views: 100

Answers (2)

techBeginner
techBeginner

Reputation: 3850

you can use reflection inside the orderBymethod..something like

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

I haven't tested this code..this just an idea..

Upvotes: 0

Andy T
Andy T

Reputation: 9881

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)

Upvotes: 3

Related Questions