0

I have a variable in a javascript function which needs to be sent to the controller. This is the code in the javascript function.

var testString = "Test";

        $.ajax({
        type: "POST",
        url: "@Url.Action("GetJavaScriptString")",
            dataType: "json",
            data: JSON.stringify(testString),
        success: function (data) {
            alert(data);
        },
        failure: function (errMsg) {
            alert(errMsg);
        }
        });

And this is the controller method

    public ActionResult GetJavaScriptString(string data)
    {

        return null;
    }

The variable "data" in the GetJavaScriptString method remains null.

1
  • Its data: { data: testString }, (not data: JSON.stringify(testString),) Commented Aug 30, 2018 at 7:04

1 Answer 1

1

You need to send a name/value pair when the name matches the name of your parameter

var testString = "Test";
$.ajax({
    type: "POST",
    url: "@Url.Action("GetJavaScriptString")",
    dataType: "json",
    data: { data: testString }, // change this 
    success: function (data) {
        alert(data);
    },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

Note that you do not need JSON.stringify(), but if you did it would be data: JSON.stringify({ data: testString }), and you would need to the contentType: 'application/json', option

Sign up to request clarification or add additional context in comments.

4 Comments

No its not (and you would know that if you tested it)
Read my comment in the question
I know its now correct - you just copied my code! And your first sentence is still an incorrect statement
@StephenMuecke I'm not copying your code. can you please modify as your way.

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.