Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 928
Jason Jackson Avatar asked Sep 01 '10 22:09

Jason Jackson


People also ask

What is custom model binder?

In the MVC pattern, Model binding maps the HTTP request data to the parameters of a Controllers action method. The parameter can be of a simple type like integers, strings, double etc. or they may be complex types. MVC then binds the request data to the action parameter by using the parameter name.

How can we use register a custom model binder in asp net?

To register custom model binder, we need to create a binder provider. The model binder provider class implement IModelBinderProvider interface. The all built-in model binders have their own model binder providers. We can also specify the type of argument model binder produces, not the input of our model binder.

How does model binding works in model view controller?

How Model Binding Works. Model binding is a simplistic way to correlate C# code with an HTTP request. The model binding applies to transforming the HTTP request data in the query's form string and form collection of the action method parameters. We can consider these parameters to be primitive type or complex type.

In which of the following places will the default model binder look in order to build an object passed as a parameter to an MVC 5 controller method?

The MVC runtime uses Default ModelBinder to build the model parameters. This is done automatically by MVC Model Binder. Let us understand by a simple example how model information is passed to the controller by model binding from view in MVC.


2 Answers

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.

like image 188
bzlm Avatar answered Sep 29 '22 20:09

bzlm


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;
    }
}
like image 32
Luke Smith Avatar answered Sep 29 '22 21:09

Luke Smith