I am working with ASP.NET CORE RC2 and I have the following model binder:
public class MovieModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(MovieViewModel))
{
var idValue = bindingContext.ValueProvider.GetValue("Id").FirstValue;
var nameValue = bindingContext.ValueProvider.GetValue("Name").FirstValue;
var timespanProperty = bindingContext.ModelMetadata.Properties.Single(p => p.PropertyName == "Length");
var timespanValue = bindingContext.ValueProvider.GetValue(timespanProperty.PropertyName).FirstValue;
int minutes;
int.TryParse(timespanValue, out minutes);
int id;
int.TryParse(idValue, out id);
var model = new MovieViewModel
{
Length = TimeSpan.FromMinutes(minutes),
Id = id,
Name = nameValue
};
return Task.FromResult(ModelBindingResult.Success(bindingContext.ModelName, model));
}
return Task.FromResult(default(ModelBindingResult));
}
}
I am using it on a controller action like this:
[HttpPost]
public IActionResult Create([ModelBinder(BinderType = typeof(MovieModelBinder))] MovieViewModel model)
{
// Code here
}
Problem is that I get a null model every time. What is exactly wrong with the ModelBindingResult.Success method and what change should be made to return correct results?
I'm not sure whats wrong, for me same code stopped working after rc2 update.
For workaround just manually assign :
bindingContext.Result = ModelBindingResult.Success(bindingContext.ModelName, model);
before
return Task.FromResult(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With