开发者

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜