Search code examples
asp.net-mvclistboxwebgrid

mvc3 webgrid filter with listbox


I have a webgrid with sorting and paging enabled. I also have some dropdownlists and listboxes on the same view to filter the webgrid result.

The filters are placed inside a form with http get method. I applied jquery on the filters to submit the form so every time when the filter changes, the form posts back with the selected value as querystring in the url. When multiple values are selected in listbox, the querystring generated looks like

type=1&type=3

So I created a int[] type to accept the parameters in my action. However when I sort or page the webgrid, the querystring is rewritten to

type=1,3&page=4,

in which case the type argument becomes null, the listbox is unselected and amended with a "input-validation-error" class automatically.

I actually prefer the style of the querystring generated by webgrid

type=1,3

so I can pass it directly into my query. However, it seems the listbox doesn't like this kind of the querystring. Is there a way to make the listbox to recognise the combined querystring or I have to write code to handle the querystring and selected items?


Solution

  • Thanks. I ended up by doing the similar job in a customized model binder

    class MultiSelectionBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;
            ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
            if (val != null && !string.IsNullOrEmpty(val.AttemptedValue))
            {
                bindingContext.ModelState.SetModelValue(key, val);
    
                string incomingString = ((string[])val.RawValue)[0];
                if (incomingString.Contains(","))
                {
                    var value = new ValueProviderResult(incomingString.Split(','), string.Empty, CultureInfo.InvariantCulture);
                    bindingContext.ModelState.SetModelValue(key, value);
                    return value.ConvertTo(typeof(int[]));
                }
    
                return val.ConvertTo(typeof(int[]));
            }
    
            return null;
        }
    }
    

    And applied it to the arguments

    public ViewResult Index([ModelBinder(typeof(MultiSelectionBinder))] int[] type, ...)