Pergunta

I have a third party control that utilizes a single hidden input field to store a list of integers. This control is used throughout the site on numerous forms.

The submitted value (as displayed in Fiddler) is:

items=1,35,346,547

The controller action looks like:

public ActionResults SomeAction(IEnumerable<int> items) {...}

As expected, the DefaultModelBinder fails to parse the list of integers. Given that I do have the ability to change the format of the input value, is there a format that would enable the default model binder to parse this for me?

I could easily change the action to have a string parameter and handle the parsing myself, however I'd like the model binder to do this for me. I could also intercept the form submit and scrape/change the data/data-type to JSON (or someother format), however I'd really like to avoid this approach. Another option would be to create a custom model binder, but this seems like it might be a bit of overkill.

Recommendations?

Foi útil?

Solução

Description

No the Default Model Binder can't do this. You can create a custom Model Binder that handle that. Asuming your input field name is items my sample should work, if not change it to the right name.

Sample

public class MyCustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        List<int> result = new List<int>();

        var value = bindingContext.ValueProvider.GetValue("items").AttemptedValue;

        foreach (string i in value.Split(",".ToCharArray()))
        {
            int a;
            if (Int32.TryParse(i, out a))
                result.Add(a);
        }
        
        return result;
    }
}

public ActionResult SomeAction([ModelBinder(typeof(MyCustomModelBinder))] List<int> list)

More Information

Update

You can register your Custom Model Binder in global.asax

  ModelBinders.Binders.Add(typeof(List<int>), new MyCustomModelBinder());

but be aware that this would always try to bind if you have List<int> in your Action Method.

According to your comment: There is no way, at the moment, that makes it possible to say the Default Model Binder to do that because he try to bind the properties and don't know when you want to bind List<int>and when not.

You can see the source of the DefaultModelBinder here

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top