How to pass data to controller using Fetch api in asp.net core

Viewed 25345

I post data using fetch like this in my client js scripts

    fetch('/myarea/mycontroller/myaction', {
        method: 'post',
        body: JSON.stringify({ name: namevalue, address: addressvalue })
    })
        .then(function (response) {
            if (response.status !== 200) {
                console.log('fetch returned not ok' + response.status);
            }

            response.json().then(function (data) {
                console.log('fetch returned ok');
                console.log(data);
            });
        })
        .catch(function (err) {
            console.log(`error: ${err}`);
        });
    }, false);

Then on my controller

    [HttpPost]      
    public async Task<IActionResult> MyAction(string name, string address)
    {
        // Error, name and address is null here, shouldn't be!
        // more code here ...
    }

My controller action is being called correctly, and I am able to debug inside it, but no data being passed. What could be wrong here? Thanks

3 Answers

The [FromBody] attribute kicked in for me only after I defined the header that it is an "application/json" type:

fetch('api/Profile/Update', {
        method: 'post',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ description: "Some text here" })
    });

And this is how the controller action looks like:

    [HttpPost("[action]")]
    public async Task<IActionResult> Update([FromBody] ProfileUpdateModel profileUpdateModel)
    {
        //Do some stuff here...
        return  RedirectToAction("/", "HomeController");
    }

And the description property now receives the value from the request. Hope this gives final clarity to somebody tackling with the issue.

Or if you had <form>...</form> you could use

fetch('/url', {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: $('#editContactModal form').serialize() 
    // body like "id=1&clientid=3&name=me&phones=123&email=@mail.com"
})

without [FromBody] !!! (just with regular action method in controller)

Related