Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model binding not working for nested object

I am trying to bind data in my model posted from postman in my below model:

public class VariantModel
{
    public int Id { get; set; }     
    public List<SubvariantModel> Subvariants { get; set; }
}

public class SubvariantModel
{
    public int Id { get; set; }
    public string Description { get; set; }
    public IFormFile Document { get; set; }
}

Every property is getting populated but only Document property is coming null as you can see here :

enter image description here

But surprisingly when i inspect http request object i see that file :

enter image description here

This is how i am posting data from POSTMAN : enter image description here

enter image description here

Code :

[HttpPost]
public void Post([FromForm]VariantModel emp)
{
    var d = HttpContext.Request;
}

Can anybody tell me what could be the issue here?

Update :

enter image description here

like image 219
ILoveStackoverflow Avatar asked Apr 05 '19 14:04

ILoveStackoverflow


People also ask

How do I fix binding issues with a view model?

Hence the binding was actually happening but crashing. Basically when you get this issue, use Fiddler to look at posted data, make sure the posted variables match the properties (not fields!) on your view models, and put a break point on the View Model constructor to ensure the Routing Engine hits the correct POST method. Good luck!

What is the use of model binding?

Model binding automates this process. The model binding system: Retrieves data from various sources such as route data, form fields, and query strings. Provides the data to controllers and Razor pages in method parameters and public properties.

Can a model binder bind disabled inputs?

Also late to join the party, but after 3 years of asp.net mvc, I've came across that disabled inputs are not posted, so the model binder cannot bind them of course. See here: "Disabled elements in a form will not be submitted".

Why is my default modelbinder not working?

For anyone else still experiencing an issues with this, if you name your parameter in your post method to be the same as one of your properties, the default modelbinder will also fail. Show activity on this post. Mine was a bit unique case, but hope it helps someone in similar context.


1 Answers

This is an issue I encountered as well. It is a known issue with nesting IFormFile as a View Model property in .NET Core v2.2.

The fix that worked for me is here.

like image 166
Graham Meehan Avatar answered Oct 07 '22 03:10

Graham Meehan