2

I'm trying to follow the steps in this article using a vNext project and mvc 6. I've been reading through the code here but still a little unsure how to implement this.

Does anyone have a working example they could share or point me in the right direction?

I'm particularly wondering how to register the custom binder, and what classes I would inherit from since DefaultModelBinder is not available.

Eilon
  • 25,582
  • 3
  • 84
  • 102

3 Answers3

5

Sample model binder: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.Core/ModelBinding/CancellationTokenModelBinder.cs

How to register the binder in Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddMvc().Configure<MvcOptions>(options => 
    { 
        options.ModelBinders.Add(typeof(MyModelBinder)); 
    });
Yishai Galatzer
  • 8,791
  • 2
  • 32
  • 41
Victor Hurdugaci
  • 28,177
  • 5
  • 87
  • 103
  • Beta5 must have changed, `Add` now requires `new MyModelBinder()` – fiat Jul 31 '15 at 01:35
  • this is no longer true, this commit replaced ModelBinders property with ModelBinderProviders property https://github.com/aspnet/Mvc/commit/fb81a5e11ead9866b2ecf6851168230b44327085 – Piotr Owsiak Jul 14 '16 at 13:41
1

I have made a blog post that contains sample of trimming strings automatically in the model.

Blog post is here http://hotzblog.com/asp-net-vnext-defaultmodelbinder-and-automatic-viewmodel-string-trim/

I noticed that adding directly to model binders won't work totally, because model binders are used in order. You will have to first remove the original model binder

  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());
   });
Tuukka Lindroos
  • 1,270
  • 10
  • 14
0

This is my implementation of the MVC 6 RC1 custom Model Binder though I must admit that it's not perfect yet. For some reason the getters of the ViewModel are getting hit before the values are bound to them, so we have to add if (xID == 0) checks, which is lame... and I'm still looking for a solution, anyways, this should help out some: https://github.com/Serjster/IOCModelBinderExample

Feel free to contribute if you happen to find a solution.

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183