Associates a QueryString string with arrays with MVC

I use a Telerk Kendo UI grid that loads data remotely. QueryStringpassed to my action method looks like this: -

take=10&skip=0&page=1&pageSize=10&sort[0][field]=value&sort[0][dir]=asc

I'm trying to figure out how to bind a parameter sortto my method? Is it possible, or do I need to list through the collection QueryStringmanually or create my own binder?

So far I have tried this: -

public JsonResult GetAllContent(int page, int take, int pageSize, string[] sort)

public JsonResult GetAllContent(int page, int take, int pageSize, string sort)

but sorting is always zero. Does anyone know how I can achieve this?

I can return to using Request.QueryString, but this is a bit shred.

var field = Request.QueryString["sort[0][field]"];
var dir = Request.QueryString["sort[0][dir]"];
+5
source share
1 answer

You can use an array of dictionaries:

public ActionResult Index(
    int page, int take, int pageSize, IDictionary<string, string>[] sort
)
{
    sort[0]["field"] will equal "value"
    sort[0]["dir"] will equal "asc"
    ...
}

and then define a custom mediator:

public class SortViewModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var modelName = bindingContext.ModelName;
        var keys = controllerContext
            .HttpContext
            .Request
            .Params
            .Keys
            .OfType<string>()
            .Where(key => key.StartsWith(modelName));

        var result = new Dictionary<string, string>();
        foreach (var key in keys)
        {
            var val = bindingContext.ValueProvider.GetValue(key);
            result[key.Replace(modelName, "").Replace("[", "").Replace("]", "")] = val.AttemptedValue;
        }

        return result;
    }
}

which will be registered in Global.asax:

ModelBinders.Binders.Add(typeof(IDictionary<string, string>), new SortViewModelBinder());
+7
source

All Articles