<< Back to Blog

21 NOVEMBER 2019

.NET Core: Custom Model Binder (for single field)

This example shows how to filter out specific sequences of characters from a user input string when binding it to a model property:

public class SpecialStringBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var fieldName = bindingContext.FieldName;
        if (string.IsNullOrEmpty(fieldName))
        {
            throw new Exception("Field name not found");
        }

        // Try to fetch the value of the argument by name
        var valueProviderResult = bindingContext.ValueProvider.GetValue(fieldName);

        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(fieldName, valueProviderResult);

        var value = valueProviderResult.FirstValue;

        if (string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }

        string model = value.Replace("\r\n", string.Empty);

        bindingContext.Result = ModelBindingResult.Success(model);
        return Task.CompletedTask;
    }
}

Add to property in model:

public class MyModel {
        [ModelBinder(BinderType = typeof(SpecialStringBinder))]
        public string SpecialString { get; set; }
}