Sachin Erande
Sachin Erande

Reputation: 11

ASP.NET Core 3.1 - Json Request property to action method parameter model binding

I am migrating an app from ASP.NET MVC to ASP.NET Core MVC.

Looks like ASP.NET Core model binding doesn't support binding of top level properties of json object to action method property binding (this was supported in ASP.NET MVC framework).

Example: I have an action method like this:

ActionResult UpdateSomethingOnPost(string name, string id) { }

I am posting Json body as below. It doesn't bind property "name" to "name" action method parameter, also "id" to "id" action method parameter.

{
    name: "Sachin",
    id: "1000"
}

What changes do I need to make to let this supported in ASP.NET Core?

Upvotes: 1

Views: 1206

Answers (1)

Bemn
Bemn

Reputation: 1391

How about adding the [HttpPost] and [FromBody] attributes?

[HttpPost]
ActionResult UpdateSomethingOnPost([FromBody]string name, [FromBody]string id)
{
  // blah blah blah 
}

This post mentions that for simple types you need to add the [FromBody] attribute:

FromBody inference notes

[FromBody] isn't inferred for simple types such as string or int. Therefore, the [FromBody] attribute should be used for simple types when that functionality is needed.

Upvotes: 1

Related Questions