This Article helps to understand the concept of Custom Model Binding in ASP.NET Core MVC
Custom Model Binding helps, when you have special data or formats that the built-in model binders don't support
Step 1: Create the Custom Model Binder:
Implement the IModelBinder interface. The BindModelAsync method must be implemented in order to use IModelBinder interface.
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace WebApplication3.ModelBinders
{
public class QueryStringToArrayModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
try
{
var queryString = bindingContext.HttpContext.Request.Query;
var UserIds = queryString["userIds"].ToString();
if (string.IsNullOrEmpty(UserIds))
{
return Task.CompletedTask;
}
var values = UserIds.Split(',').Select(int.Parse).ToList();
bindingContext.Result = ModelBindingResult.Success(values);
return Task.CompletedTask;
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError("Error", "Received Input cannot be parsed");
return Task.CompletedTask;
}
}
}
}
Step 2: Create a Model Binder Provider:
Implement the IModelBinderProvider interface. this helps ASP.NET to determine when to use your custom binder.
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace WebApplication3.ModelBinders
{
public class QueryStringToArrayModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(List<int>))
{
return new QueryStringToArrayModelBinder();
}
return null;
}
}
}
Step 3: Register Your Custom Binder:
Register your custom binder to the MVC options during application startup.
// Register in Program.cs file
builder.Services.AddControllersWithViews(options =>
{
options.ModelBinderProviders.Insert(0, new QueryStringToArrayModelBinderProvider());
});
Step 4: Using Custom Binder:
namespace WebApplication3.Controllers
{
public class StudentController : Controller
{
public IActionResult Detail([ModelBinder(typeof(QueryStringToArrayModelBinder))] List<int> Ids)
{
return Ok(Ids);
}
}
}
Step 5: Run
/student/detail?Ids=10,20,30