ASP.NET Core MVC Interview Question #167

What is a custom model binder?

Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced

Quick Interview Answer

A custom model binder controls how request data is converted into a particular parameter or model type when the default binding behavior is not sufficient. It implements model-binding contracts and can be associated with a type or configured through a provider.

Detailed Explanation

A custom model binder controls how request data is converted into a particular parameter or model type when the default binding behavior is not sufficient. It implements model-binding contracts and can be associated with a type or configured through a provider.

Custom binders should be reserved for genuine reusable binding requirements. Ordinary validation, business lookups, and persistence logic should not be moved into model binders merely to reduce controller code.

Code Example

public class ProductKeyBinder : IModelBinder
{
    public Task BindModelAsync(
        ModelBindingContext context)
    {
        var value = context.ValueProvider
            .GetValue(context.ModelName)
            .FirstValue;

        // Parse and set binding result.
        return Task.CompletedTask;
    }
}