Home > Enterprise >  ASP.NET Core MVC controller not binding
ASP.NET Core MVC controller not binding

Time:03-16

Doing a request from the fetch api to the endpoint and the props do not bind.

The id and fileName are 0 and null respectively on the endpoint.

My fetch:

fetch(`https://localhost:44343/items/edit`, {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id:123,
                fileName:"asd"
            })
        })
            .then(response => console.log(response))
            .catch(error => console.error('Unable to update item.', error));

My endpoint:

[HttpPost]
public async Task<IActionResult> Edit([FromBody]int id, string fileName)
{
    return Ok(id);
}

The request payload shows that the values are being sent:

network request

I've tried using and not using the [FromBody] adding explicitly the route to the action, changing to PUT instead of POST (why the heck does the default for the update action is a POST??)

Anything else I can try?

CodePudding user response:

Create a class which will represent the json structure:

public class Request
{
   public int id {get; set;} 
   string fileName {get; set;} 
}

And accept it in the action:

public async Task<IActionResult> Edit(Request r)
{
   // use r
}

More on model binding in ASP.NET Core.

CodePudding user response:

As stated in previous comment, create an object model to represent the json

public class Request
{
   public int Id {get;set;}
   public string FileName {get;set;}
}

At your controller action method

   [HttpPost]
   [Route("items/edit")]
   public IActionResult Edit([FromBody] Request req)
   {
     return Ok();
   }
  • Related