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