I'm trying to figure out model binding in current mvc6 (visual studio 2015 release candidate). This is what my code looks like so far:
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);
}
}
The 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 yet about actually creating the object from the input, what troubles me is that when I debug, I see the controller firing (with x being null), but the binder function is not being called. Any ideas of what's wrong here?
[EDIT: This has already been updated]Also note, I have already seen What is the correct way to create custom model binders in MVC6? but the answer in that post is either wrong or outdated, since the example provided doesn't implement the current IModelBinder.
Thanks
EDIT: This is the javascript code used to fire 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) }
});
}
Remove the
[FromBody]
decoration on the action's parameter.FromBody
is indicated that anInputFormatter
is to be used to populate this parameter. If you remove it model binders run.Try to add it as the first model binder into the list. When an
IModelBinder
successfully sets a model, otherIModelBinder
won't be fired.So if you want to give a chance to your own
IModelBinder
you have to make it being fired before others do the job.This works for me:
But index
0
is not the best place to put it. Just determine which ModelBinder sets the model and prevents your ModelBinder to be fired and put your ModelBinder before it.Add
to method or u can set default binder for type