Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to bind ExtJs 4 Grid filter info to asp.net mvc action parameters?

What's the best way to bind ExtJs 4 Grid filter info to asp.net mvc action parameters?

I wrote these helper classes:

public class ExtFilterInfo
{
    public string Field { get; set; }
    public ExtFilterData Data { get; set; }
}

public class ExtFilterData
{
    public string Type { get; set; }
    public string Value { get; set; }
}

Here is the Action:

public ActionResult Grid(int start, int limit, string sort, ExtFilterInfo[] filter)

The QueryString looks something like this:

_dc:1306799668564
filter%5B0%5D%5Bfield%5D:Nome
filter%5B0%5D%5Bdata%5D%5Btype%5D:string
filter%5B0%5D%5Bdata%5D%5Bvalue%5D:nu
page:1
start:0
limit:20
like image 511
Vinicius Rocha Avatar asked Oct 10 '22 21:10

Vinicius Rocha


1 Answers

A custom model binder looks like it could fit the bill:

public class ExtFilterInfoModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var filter = (ExtFilterInfo)base.BindModel(controllerContext, bindingContext);

        var field = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[field]");
        if (field != null)
        {
            filter.Field = field.AttemptedValue;
        }

        var type = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[data][type]");
        if (type != null)
        {
            if (filter.Data == null)
            {
                filter.Data = new ExtFilterData();
            }
            filter.Data.Type = type.AttemptedValue;
        }

        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[data][value]");
        if (value != null)
        {
            if (filter.Data == null)
            {
                filter.Data = new ExtFilterData();
            }
            filter.Data.Value = value.AttemptedValue;
        }

        return filter;
    }
}

which could be registered in Application_Start:

ModelBinders.Binders.Add(typeof(ExtFilterInfo), new ExtFilterInfoModelBinder());

and now the filter collection which your controller action takes as argument should be bound correctly.

like image 60
Darin Dimitrov Avatar answered Oct 26 '22 22:10

Darin Dimitrov