0

I am working on a web application using Asp.Net Core 3.1, i make ajax call(using axios library, method is POST):

<script>
    axios({
        url: '/home/test', // HomeController/Test Action
        method: 'post',
        data: {
            abc: 123
        },
    })
        .then(function (response) {
        console.log(response);
    })
        .catch(function (error) {
            console.log(error);
        });
</script>

in my HomeController i have appropriate action:

[HttpPost]
public IActionResult Test(string abc)
{
    return Json(new { abc });
}

in this case binding doesn't work well even if i add [FromBody] attribute like:

[HttpPost]
public IActionResult Test([FromBody]string abc)
{
    return Json(new { abc });
}

what is a solution in this case?

Nick Money
  • 89
  • 2
  • 6

2 Answers2

1

You can use FormData() to pass axios data to controller:

 <script>
        var bodyFormData = new FormData();
        bodyFormData.set('abc', 123);
        axios({
            url: '/Home/test', // HomeController/Test Action
            method: 'post',
            data: bodyFormData,
        })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    </script>

Here is the test result:

enter image description here

LouraQ
  • 6,443
  • 2
  • 6
  • 16
  • @NickMoney, if this helps you, please accept it as the answer . This will help other people with similar problems to find the answer as soon as possible. – LouraQ Jun 22 '20 at 14:21
0

Sometimes the binding FromBody can't parse the html content from the body. Try to change the parameter type from string to dynamic. It should hit your controller. You can wrap your parameter into a class that has only that field and there the binding works.

Also you can take advantage of the action constraints and try that as well

HttpPost("{abc:string}")

Hope this help

Zinov
  • 3,817
  • 5
  • 36
  • 70