reactjsasp.net-coreaxiosasp.net-core-webapi

Why axios not submitting data to ASP.NET Core Web API


I am trying to send data from React app to my ASP.NET Core Web API with the help of Axios, but I'm not getting the data.

Axios code:

    axios.put(urlPath,
                {
                        method: 'put',
                        data: {
 PageDbId: "Soursbh",
            UserDbId:""
}
                    })
                .then(response => onSuccess(response))
                .catch(e => onError(e));

ASP.NET Core model class:

public class WebAvatarModel
{
    public string PageDbId { get; set; }
    public string UserDbId { get; set; }
}

ASP.NET Core code:

[HttpPut]
public IActionResult Save_Avatar([FromBody] WebAvatarModel model)
{
    var users = model;
    
    return null;
}

Always getting null in PageDbId and UserDbId.

I also tried this:

await axios.put(urlPath, JSON.stringify(body),
                {
                    method: 'put',
                    headers: {'Content-Type': 'application/json'}
                })
            .then(response => onSuccess(response))
            .catch(e => onError(e));

[HttpPut]
public async Task<IActionResult> Save_Avatar(WebAvatarModel model)
{
    var users = model;
    return null;
}

But it's still not working. What am I doing wrong?


Solution

  • Always getting null in PageDbId and UserDbId

    If you check the actual request payload using browser developer tool, you would find that the data look like below.

    enter image description here

    You need to modify your code as below to provide correct request payload.

    axios.put(urlPath,
        {
            PageDbId: "Soursbh",
            UserDbId: ""
        })
        .then(response => onSuccess(response))
        .catch(e => onError(e));
    

    Or

    axios({
        method: 'put',
        url: urlPath,
        data: {
            PageDbId: "Soursbh",
            UserDbId: ""
        }
    })
        .then(response => onSuccess(response))
        .catch(e => onError(e));
    

    Test Result

    enter image description here