stefan.stt
stefan.stt

Reputation: 2627

Sending data to MVC Controller with AJAX

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 :(
}

Upvotes: 0

Views: 988

Answers (2)

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10512

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
    ...
}

Upvotes: 1

zetawars
zetawars

Reputation: 1071

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 :(
}

Upvotes: 1

Related Questions