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

I am posting data using fetch like this in 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 can debug it, but no data is passed. What could be wrong here? Thanks to

+3


source to share


1 answer


The controller action is waiting for request parameters ( /myaction?name=myname&address=myaddress

). This is the default. You send them to the body.

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



Or you can say that the controller action takes 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; }
}

      

+2


source







All Articles