Custom model binding
Built-in model binding handles simple types and objects made of them. When a value arrives in a custom format, such as "12.97,77.59" for a map point, you can teach MVC to bind it. This lesson shows a custom IModelBinder and when simpler options are enough.
- StartAction needs a GeoPointpublic IActionResult Near(GeoPoint location)
- Step 2MVC picks your binder[ModelBinder(typeof(GeoPointBinder))] on the type
- Step 3Binder reads the raw valueValueProvider gets "12.97,77.59" from the query string
- Step 4Binder parses itSplits the text and converts it to numbers
- EndResult is setSuccess with a GeoPoint, or an error added to ModelState
The idea in plain words
A model binder is the code that turns request text into a .NET object. MVC has binders for numbers, dates, strings, collections and complex types. When your type does not fit, you write a class implementing IModelBinder and attach it to the type or parameter.
Before writing a binder, check the simpler options. A type with a public static TryParse method or a TypeConverter can often be bound from a single string without a custom binder.
Example: the binder
[ModelBinder(BinderType = typeof(GeoPointBinder))]
public record GeoPoint(double Lat, double Lng);
public class GeoPointBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext context)
{
var raw = context.ValueProvider.GetValue(context.ModelName).FirstValue;
if (string.IsNullOrEmpty(raw))
return Task.CompletedTask; // nothing to bind
var parts = raw.Split(',');
if (parts.Length == 2 &&
double.TryParse(parts[0], CultureInfo.InvariantCulture, out var lat) &&
double.TryParse(parts[1], CultureInfo.InvariantCulture, out var lng))
{
context.Result = ModelBindingResult.Success(new GeoPoint(lat, lng));
}
else
{
context.ModelState.AddModelError(context.ModelName, "Use the format lat,lng.");
}
return Task.CompletedTask;
}
}Using it
Because the type carries the [ModelBinder] attribute, any action parameter of that type uses the binder. To apply a binder without touching the type, implement IModelBinderProvider and insert it into MvcOptions.ModelBinderProviders.
// GET /stores/near?location=12.97,77.59
public IActionResult Near(GeoPoint location)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
return View(_stores.FindNear(location.Lat, location.Lng));
}Common mistakes
- Throwing exceptions from a binder instead of adding a ModelState error.
- Parsing numbers with the current culture, so 12.97 fails on servers using a comma decimal separator.
- Doing database lookups in binders for every request without thinking about cost.
Interview question
How do you create and register a custom model binder in ASP.NET Core?
Implement IModelBinder and its BindModelAsync method: read the value with bindingContext.ValueProvider.GetValue(ModelName), convert it, and set bindingContext.Result to ModelBindingResult.Success(value), or add an error to ModelState. Apply it with [ModelBinder(BinderType = typeof(MyBinder))] on the type or parameter, or create an IModelBinderProvider and insert it into MvcOptions.ModelBinderProviders so it is used for a type globally.
Want the full details? Read the official Microsoft documentation for this topic.