asp.net mvc 3 webgrid sorting remains ?sortdir=ASC

后端 未结 4 1073
谎友^
谎友^ 2021-02-04 08:54

I\'m experimenting a bit with several grids in asp.net mvc. Microsoft has a grid too know in the prerelease of mvc 3 so I thought I\'ll try that one out.

The basic funct

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 09:08

    I've been thinking about a workaround for the problem, and I've found one.

    I inject an extra parameter into the querystring collection. That way I can put the search filter into the querystring.

    Normally the querystring collection is readonly, but I've found some code to fix this.

    Code to add parameter to querystring:

                public static void Add(string name, string value)
                {
                        NameValueCollection qs = System.Web.HttpContext.Current.Request.QueryString;
                        qs = (NameValueCollection)System.Web.HttpContext.Current.Request.GetType().GetField("_queryString", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(System.Web.HttpContext.Current.Request);
                        PropertyInfo readOnlyInfo = qs.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
                        readOnlyInfo.SetValue(qs, false, null);
                        qs[name] = value;
                        readOnlyInfo.SetValue(qs, true, null);
                }
    

    New controller code:

                public ActionResult Index(string SearchFilter)
                {
                        // check querystring search
                        if (string.IsNullOrEmpty(SearchFilter) && !String.IsNullOrEmpty(Request.QueryString["search"]))
                                SearchFilter = Request.QueryString["search"];
    
                        var model = new Models.SubscriptionListModel { SearchFilter = SearchFilter };
    
                        if (string.IsNullOrEmpty(SearchFilter))
                        {
                                model.SubscriptionList = _subscriptionHandler.ReadWhereIdLessThanThousand();
                        }
                        else
                        {
                                // add search filter to the querystring
                                Common.QueryString.Add("search", SearchFilter);
                                model.SubscriptionList = _subscriptionHandler.ReadWhereContains(SearchFilter);
                        }
    
                        if (Request.IsAjaxRequest())
                        {
                                return View("SubscriptionList", model);
                        }
                        else
                        {
                                return View("Index", model);
                        }
                }
    

    If anyone has a cleaner solution to fix this, suggestions are still welcome :-)

提交回复
热议问题