0

I am trying to send data with AJAX to MVC Controller method, but I don't know what am I doing wrong.

Here is the AJAX call

$.ajax({
    type: 'POST',
    url: invokingControllerActionUrl,
    data: "it is just a simple string",
    success: function (data) {
        window.location.href = link;
    }
});

And here is the controller method. It is invoked, but the parameter is always null.

public IActionResult OnPostTest([FromBody] string stringValue)
{
    // stringValue is always null :(
}
stefan.stt
  • 2,357
  • 5
  • 24
  • 47

2 Answers2

1

Depending on what Content-Type you are sending from JS, you might need to encode your string properly, as a form-value

...
data: 'stringValue="it is just a simple string"',
...

or e.g. JSON:

...
data: '{stringValue: "it is just a simple string"}',
...

See also this discussion

I haven't found an easy way to pass a string of unformatted data via parameter, unfortunately. According to this answer, you can do the following:

public IActionResult OnPostTest()
{
    Stream req = Request.Body;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string stringValue = new StreamReader(req).ReadToEnd();
    ...
    // process your stringValue here
    ...
}
Sergey Kudriavtsev
  • 10,328
  • 4
  • 43
  • 68
1

Change you ajax call to this

$.ajax({
    type: 'POST',
    url: invokingControllerActionUrl, // Confirm the Path in this variable Otherwise use @Url.Action("OnPostTest", "InvokingController")
    data: {stringValue: "it is just a simple string"},
    success: function (data) {
        window.location.href = link;
    }
});

And remove the [FromBody]. ALso its better to define type post. Not necessary though

[HttpPost]
public IActionResult OnPostTest( string stringValue)
{
    // stringValue is always null :(
}
zetawars
  • 1,023
  • 1
  • 12
  • 27