Mvc6 regular binder model does not fire

I'm trying to figure out model binding in current mvc6 (Visual Studio 2015 release candidate). This is my code looks like this:

public class MyObjectModelBinder : IModelBinder
{
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {

        if (bindingContext.ModelType == typeof(MyObject))
        {
            var model = new MyObject();
            return Task.FromResult(new ModelBindingResult(model, bindingContext.ModelName, true));
        }
        return Task.FromResult<ModelBindingResult>(null);

    }
}

      

Registration in startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.ModelBinders.Add(typeof( MyObjectModelBinder));
    });
}

      

My controller:

[HttpPost]
public void ReceiveMyObject([FromBody] MyObject x)
{

}

      

I don't care that I am actually creating an object from the input, what worries me is that when I debug, I see the controller start up (with x being null), but the bind function is not called. Any ideas on what is wrong here?

[EDIT: this has already been updated] Also note that I've already seen What is the correct way to create custom model bindings in MVC6? but the answer in this post is either wrong or outdated as the example provided does not implement the current IModelBinder.

thank

EDIT: This is the javascript code used to start the controller:

function sendMessage(i) {
    $.ajax({
        type: 'POST',
        url: 'myurl',
        data: data,
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) { console.log(data) }
    });
}

      

+3


source to share


3 answers


Add to

public void ReceiveMyObject([ModelBinder(BinderType = typeof(MyObjectModelBinder))] MyObject x)

      



to the method or u can set the default binding for the type

+2


source


Remove decor [FromBody]

by action parameter.



FromBody

specifies what to use to populate this parameter InputFormatter

. If you remove it, then bindings to them will be performed.

+1


source


Try adding it as the first attachment to your list. When the IModelBinder

model is successfully installed, the others IModelBinder

will not be launched.

So, if you want to give your own a shot IModelBinder

, you have to get them to be fired before others do.

This works for me:

services.Configure<MvcOptions>(options =>
{
    options.ModelBinders.Insert(0, new MyObjectModelBinder());
});

      

But the index 0

is not the best place to put it. Just define which ModelBinder sets the model and prevents your ModelBinder from starting and puts your ModelBinder in front of it.

+1


source







All Articles