Matthew Pavia
Matthew Pavia

Reputation: 7

ASP.NET MVC - How to pass a Javascript variable from view to controller

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.

Upvotes: 0

Views: 1685

Answers (1)

Kiran Joshi
Kiran Joshi

Reputation: 1876

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

Upvotes: 1

Related Questions