Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNet Core RC2 Model binding gives null model

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?

like image 285
gdyrrahitis Avatar asked Jan 24 '26 18:01

gdyrrahitis


1 Answers

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(...)
like image 190
user1214919 Avatar answered Jan 26 '26 10:01

user1214919



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!