3

I have the following ajax request in which I'm trying to send a JSON Object to the server:

function sendData(subscriptionJson) {




                $.ajax({
                    type: "POST",
                    url: '@Url.Action("SubscribeSecurities", "Subscription")',
                    data: "{'subscriptions': subscriptionJson}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        console.log("success response: " + response.responseText);
                        alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);

                    },
                    failure: function (response) {
                        console.log("failure response: " + response.responseText);
                        alert(response.responseText);
                    },
                    error: function (response) {
                        console.log("error response: " + response.responseText);
                        alert(response.responseText);
                    }
                });


            }

Based on the top answer in this post I added quotes around the "data" attribute, but I'm getting an error saying that the "subscriptionJSON" isn't being recognized. I tried testing with a sample string as is done in the post: data: "{'foo':'foovalue', 'bar':'barvalue'}", but when the controller gets the parameter of the subscriptionJson object it is null.

What is the official way to send a JSON object via a POST request to an ASP .NET MVC controller?

loremIpsum1771
  • 2,497
  • 5
  • 40
  • 87

2 Answers2

3

Your issue is because you're not sending valid JSON. You need to wrap the keys in double quotes. Also, subscriptionJson is a literal string in your code. You need it to be a string variable.

data: '{"subscriptions": ' + subscriptionJson + '}',

Or, even better, just provide a plain object to jQuery and let it encode the values for you:

data: { subscriptions: subscriptionJson },
Sam Axe
  • 33,313
  • 9
  • 55
  • 89
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

create a simple java script object just before Ajax statement. Build ajax options with data as

data : { parameterName : jsobject }

Note: (No quotes)

Make sure the controller action method has same parameterName.

Dhanasekar Murugesan
  • 3,141
  • 1
  • 18
  • 21