Jason Jackson
Jason Jackson

Reputation: 17260

Using a custom model binder for an argument of a controller action

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".

Upvotes: 5

Views: 2690

Answers (2)

bzlm
bzlm

Reputation: 9727

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.

Upvotes: 11

Luke Smith
Luke Smith

Reputation: 24244

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;
    }
}

Upvotes: 6

Related Questions