What's the correct way to create custom model bindings in MVC6?
I'm trying to follow the steps in this article using the vNext project and mvc 6. I've read the code here but still a little unsure how to implement this.
Does anyone have a working example that they could share or point me in the right direction?
I am especially interested in how to register a custom binder and which classes I inherit since the DefaultModelBinder is not available.
Binding sample example: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.Core/ModelBinding/CancellationTokenModelBinder.cs
How to register a binder in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().Configure<MvcOptions>(options =>
{
options.ModelBinders.Add(typeof(MyModelBinder));
});
source to share
I made a blog post that automatically contains a sample of trim lines in the model.
The blog post is here http://hotzblog.com/asp-net-vnext-defaultmodelbinder-and-automatic-viewmodel-string-trim/
I noticed that adding directly to the model bindings would not work completely because the model bindings are used in order. You will need to remove the original binder first
services.AddMvc().Configure(options =>
{
// Replace MutableObjectModelBinder with extended Trimmer version
IModelBinder originalBinder = options.ModelBinders.FirstOrDefault(x=>x.GetType() == typeof(MutableObjectModelBinder));
int binderIndex = options.ModelBinders.IndexOf(originalBinder);
options.ModelBinders.Remove(originalBinder);
options.ModelBinders.Insert(binderIndex, new TrimmingModelBinder());
});
source to share
This is my MVC 6
RC1
custom implementation Model Binder
, although I have to admit it's not perfect yet. For some reason, getters
the ones ViewModel
get hit before the values ββare bound to them, so we need to add if (xID == 0)
checks which are lame ... and I'm still looking for a solution, anyway this should help some:
https: // github. com / Serjster / IOCModelBinderExample
Do not hesitate if you manage to find a solution.
source to share