0

ASP.NET Core 3.1 jQuery 3.3.1

I've cut down my code to the bare bones, My client side JavaScript looks like this:

    $.ajax({
        url: "/xxx/Edit",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify("Hello"),
        success: function (result) {

            //
        },
        error: function (jqXHR) {

            //
        }

My server-side Controller Action code is:

// xxx controller
public async Task<JsonResult> Edit(string data)
{
    ...
    await ...
}

The value of data is always null. It should be "Hello".

In the real code the data is not simply a string, it is a complex type, but I have found that even with a simple string (as with a complex type) the action parameter is null???

Anyone have any ideas why the controller action does not receive "Hello" in its parameter?

9
  • 2
    Try putting data: { arg: "Hello" } and then in your controller change string data to string arg. Just to make sure it's pulling through the data. Commented Jan 7, 2020 at 11:34
  • 1
    data: { data: 'Hello' } and get rid of contentType. Also ensure that your action is configured to receive POST requests Commented Jan 7, 2020 at 11:37
  • 1
    [HttpPost] attribute is missing on the controller method Commented Jan 7, 2020 at 11:40
  • 1
    Doing what Halden and Cory said (along with removing content type) seems to have fixed the string and has fixed the complex type too. Thanks guys. Commented Jan 7, 2020 at 11:45
  • 1
    No worries, glad you figured it out. Commented Jan 7, 2020 at 11:57

1 Answer 1

2
        $.ajax({
            url: "xxx/Edit".
            type: "POST",
            data: { data: "Hello" },  // named parameter and contentType removed
            success: function (result) {

                //
            },
            error: function (jqXHR) {

                //
            }
        });

and controller action...

    public async Task<JsonResult> Edit(string data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.