Using a custom model binder for an argument of a controller action
Asked Answered
H

2

5

I have a controller action that looks like:

public ActionResult DoSomethingCool(int[] someIdNumbers)
{
    ...
}

I would like to be able to use a custom model binder the create that array of IDs from a list of checkboxes on the client. Is there a way to bind to just that argument? Additionally, is there a way for a model binder to discover the name of the argument being used? For example, in my model binder I would love to know that the name of the argument was "someIdNumbers".

Homogeny answered 1/9, 2010 at 22:14 Comment(0)
B
11

The ModelBinder attribute can be applied to individual parameters of an action method:

public ActionResult Contact([ModelBinder(typeof(ContactBinder))]Contact contact)

Here, the contact parameter is bound using the ContactBinder.

Banker answered 2/9, 2010 at 6:38 Comment(0)
B
6

To discover the name of the argument you can use the ModelBindingContext.ModelName property

public class MyModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var thisIsTheArgumentName = bindingContext.ModelName;
    }
}
Beaumarchais answered 1/9, 2010 at 22:28 Comment(1)
That approach is quite handy for re-using the same binder for multiple different arguments.Propinquity

© 2022 - 2024 — McMap. All rights reserved.