姬長信(Redy)

asp.net-mvc – ASP.NET MVC:自定义排序


我正在尝试在我的小型asp.net mvc应用程序中实现自定义排序.那里有很多可用的plgins.但这次我想自己做.

这是我的表头:

 
    
        S.No.
    
    
        @Html.ActionLink("UrlTitle", "Index", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc"? "Desc":"Asc"), SortBy = "UrlTitle" })
    
    
        @Html.DisplayNameFor(model => model.Url)
    
    
        @Html.DisplayNameFor(model => model.UrlDesc)
    

    
        @Html.DisplayNameFor(model => model.tbl_Category.CategoryName)
    

这就是行动:

public ActionResult Index(String SortOrder, String SortBy)
    {
        ViewBag.SortOrder = SortOrder;
        ViewBag.SortBy = SortBy;

        var model = ObjBs.GetAll().Where(x=>x.IsApproved == "A");
        switch(SortOrder)
        {
            case "Asc":
                model = model.OrderBy(x => x.UrlTitle);
                break;
            case "Desc":
                model = model.OrderByDescending(x => x.UrlTitle);
                break;
        }
        return View(model);
    }

目前,我可以按UrlTitle排序,它没有任何问题.但如果我也想按其他列排序,我写了这样的东西:

switch(SortBy)
        {
            case "UrlTitle":
                switch(SortOrder)
                {
                    case "Asc":
                        model = model.OrderBy(x => x.UrlTitle);
                        break;
                    case "Desc":
                        model = model.OrderByDescending(x => x.UrlTitle);
                        break;
                    default:
                        break;
                }
                break;

            case "Category":
                switch (SortOrder)
                {
                    case "Asc":
                        model = model.OrderBy(x => x.UrlTitle);
                        break;
                    case "Desc":
                        model = model.OrderByDescending(x => x.UrlTitle);
                        break;
                    default:
                        break;
                }
                break;

            case "URL":
                switch (SortOrder)
                {
                    case "Asc":
                        model = model.OrderBy(x => x.UrlTitle);
                        break;
                    case "Desc":
                        model = model.OrderByDescending(x => x.UrlTitle);
                        break;
                    default:
                        break;
                }
                break;

            default:
                break;
        }

因为我可以通过参数传递列名,而不是编写嵌套开关,所以我不能这样做:

    model = model.OrderBy(x => x.SortBy); Or, model = model.OrderBy(SortBy);

好吧,我认为当程序运行时,SortBy的值将是columnName.但它似乎不起作用.

我只是不想反复写相似的代码.如何最小化它或使其更好?