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".
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.
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 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.
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.
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
.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With