Model Binding in ASP.NET Core MVC

What is Model Binding?

Model binding maps data from HTTP requests to action method parameters. It allows you to work with strongly typed objects instead of raw request data.

Supported sources include:

Basic Example


// Controller
public class ProductsController : Controller
{
    [HttpPost]
    public IActionResult Create(Product model)
    {
        if (ModelState.IsValid)
        {
            // Save product
            return RedirectToAction("Index");
        }
        return View(model);
    }
}

// Product model
public class Product
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public decimal Price { get; set; }
}

The Product instance is automatically populated from form fields with matching names.

Binding From Query String


// Controller
public IActionResult Search(string term, int page = 1)
{
    // term and page come from the query string ?term=foo&page=2
    var results = _service.Search(term, page);
    return View(results);
}

Custom Model Binders

When default binding is insufficient, implement IModelBinder.


// Custom binder for DateTime with specific format
public class CustomDateTimeBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext context)
    {
        var value = context.ValueProvider.GetValue(context.ModelName).FirstValue;
        if (DateTime.TryParseExact(value, "dd/MM/yyyy", null,
                                   System.Globalization.DateTimeStyles.None,
                                   out var date))
        {
            context.Result = ModelBindingResult.Success(date);
        }
        else
        {
            context.ModelState.TryAddModelError(context.ModelName,
                                                "Invalid date format.");
        }
        return Task.CompletedTask;
    }
}

// Apply binder
public class Event
{
    [ModelBinder(BinderType = typeof(CustomDateTimeBinder))]
    public DateTime EventDate { get; set; }
}

Advanced Topics