1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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();
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.