What is the correct way to create custom model binders in MVC6?

后端 未结 3 734
生来不讨喜
生来不讨喜 2021-01-15 08:43

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.

3条回答
  •  情深已故
    2021-01-15 09:27

    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());
       });
    

提交回复
热议问题