Search code examples
c#asp.net-mvcasp.net-coremodel-binding

fail to combine ModelBinderAttribute and FromBody for controller action method


Following a .Net Framework to .Net Core MVC migration, The Combination between [Modelbinder] with a second complex type in a controller action parameter does not seem to work anymore.

E.g. of method which I try to call:

[HttpPost]
public ActionResult GetResult([ModelBinder(typeof(ComplexDynamicModelBinder))] dynamic dynamicFormModel, [FromBody] RandomComplexType complexType) { 
// Do Something 
}

E.g. of call from Js:

const fetchHeaders = new Headers([
   ['__RequestVerificationToken', 'myveriftoken'],
   ['x-requested-with', 'XMLHttpRequest'],
   ['Content-Type', 'application/json']
]);
fetch(urlToAction, {
   method: 'POST',
   body: JSON.stringify({
      dynamicFormModel: { someProperties: "values" },
      complexType: { someProperties: "values" }
   }),
   headers: fetchHeaders
})
.then(console.log);

All my different attempts always get a 415 ...

Thank you for your future help


Solution

  • 415 is usually a data type mismatch error. Since I don't know what your model and ComplexDynamicModelBinder are, I didn't use [ModelBinder] and built a model based on your data, you can use it as a reference.

    Model:

    public class RandomComplexType
    {
        public int Id { get; set; }
        public string Name { get; set; }
            
    }
    public class ViewModel
    { 
        public RandomComplexType complexType { get; set; }
    }
    

    JavaScript:

    const fetchHeaders = new Headers([
       ['__RequestVerificationToken', 'myveriftoken'],
       ['x-requested-with', 'XMLHttpRequest'],
       ['Content-Type', 'application/json']
    ]);
    fetch('/Home/GetResult', {
       method: 'POST',
       body: JSON.stringify({
            dynamicFormModel: { someProperties: "values" },
            complexType: { "Id": 1, "Name": "Name1" }  
       }),
       headers: fetchHeaders
    })
    .then(console.log);
    

    Test Result: enter image description here

    You can check what the data you send looks like and whether it complies with the standard in the developer tools of the browser: enter image description here