Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 594
Alexander Avatar asked Jul 05 '17 11:07

Alexander


1 Answers

The controller action is expecting query parameters (/myaction?name=myname&address=myaddress). That's the default. You're sending them in the body.

You can change the javascript to send them as query parameters. (see here: https://github.com/github/fetch/issues/256)

Or you can tell the controller action to take the values from the body:

[HttpPost]      
public async Task<IActionResult> MyAction([FromBody] Person person)
{
    var myName = person.Name;
}

public class Person
{
    public string Name {get; set; }

    public string Address {get; set; }
}
like image 136
erikbozic Avatar answered Sep 28 '22 07:09

erikbozic