SkyeBoniwell
SkyeBoniwell

Reputation: 7112

Why is the value that my controller recieves from Axios always null?

I have this simple Axios call:

 var payload = "this is a test";
 const dt = { rockText: payload };
 const request = axios.put(`/api/rocks/${rockId}/rockText`, dt);

It connects to a controller like this:

    [HttpPut("{id}/rockText")]
    public IActionResult PutRockText(Int32 id, [FromBody] string rockText)
    { ... }

But rockText is always null in the controller even though I know it's not when being used by Axios.

I've tried so many variations of the Axios call, but it's always null.

How can I get this to work?

Upvotes: 0

Views: 668

Answers (2)

Yiyi You
Yiyi You

Reputation: 18189

If you want to pass json data with axios,you need to set Content-Type,here is a demo:

axios(I use 1 to replace ${rockId} to test):

var payload = "this is a test";
const request = axios.put(`/api/rocks/1/rockText`, JSON.stringify(payload),
               { headers: { 'Content-Type': 'application/json' } });

Controller:

[HttpPut("{id}/rockText")]
public IActionResult PutRockText(int id,[FromBody]string rock)
{
     return Ok();
}

result: enter image description here

Upvotes: 2

haldo
haldo

Reputation: 16711

The issue is that the model binder cannot resolve the payload. The reason is that it's expecting a string, but you're actually passing a json object with a property rockText.

I would create a class to represent the json you're sending:

public class Rock
{
    public string RockText { get; set; }
}


[HttpPut("{id}/rockText")]
public IActionResult PutRockText(Int32 id, [FromBody] Rock rock)
{ ... }

Alternatively, you could try passing the string from axios:

var payload = "this is a test";
const request = axios.put(`/api/rocks/${rockId}/rockText`, payload);

Upvotes: 1

Related Questions