John-Luke Laue
John-Luke Laue

Reputation: 3856

How to place a Custom Model Binder on a Controller Action

I have an action that I want to place a custom Model Binder on. I do not want a global binder binder. I just want the binder on actions I specify using [ModelBinder(...)]

When I use the code below, my Binder Never gets called and neither does my action.

public IActionResult MyContactInfo([ModelBinder(BinderType = typeof(Binders.TrimModelBinder), Name = "TrimModelBinder")] MyAccountModel mam)
{
    //...
}

Stack Trace:

at Microsoft.Extensions..Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BinderTypeModelBinder.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown ---

Looks like I have to register this binder somewhere?

Upvotes: 3

Views: 951

Answers (1)

Ivan Manzhos
Ivan Manzhos

Reputation: 743

Try to remove Name property on your ModelBinder attribute and do not forget to set the actual result value in binder using the next code:

bindingContext.Result = ModelBindingResult.Success(resultModel);

Upvotes: 1

Related Questions