Reputation: 344
I am not able to see the data from my JavaScript in my Controller but I DO see the value in my Request Header. I have no clue why this isn't working....
JavaScript
$('#Save').click(function (e) {
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
url: "/Home/SaveDetails",
dataType: "json",
data: JSON.stringify({ data: "test" }),
type: "POST",
contentType: "application/json;charset=utf-8",
success: function (result) {
if (result > 0) {
alert("Worked!);
} else {
alert("There was an issue.");
}
},
complete: function () {
alert("Completed!");
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle error.
alert(errorThrown);
}
});
}
else {
alert("Form is not valid");
}
});
Controller
[HttpPost]
public ActionResult SaveDetails(string value)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
If I modify the url parameter of the ajax request above to include something like > url: "/Home/SaveDetails?username=" + 'sampleUser' I can see that data in my controller but no matter what approach I take I don't see anything sent from the ajax request using the data parameter.
Upvotes: 0
Views: 1317
Reputation: 8283
The name of the data you are sending the controller must match the name of the parameter you wish to match. In your case you are naming the data "data" and the parameter is called "value". This should fix it:
data: JSON.stringify({ value: "test" })
As an aside, you don't need to use JSON.stringify for sending your data. The following line would work just as well:
data: { value: "test" },
Also, if your data matches a class, mvc will do its best to match the data sent to the class property names:
public class MyClass
{
public int Quantity { get; set; }
public string Title { get; set; }
}
public ActionResult DoStuff(MyClass myClass)
{
//do stuff
}
Then in your ajax you could have:
data: { quantity: 32, title: 'Stuff & Things' },
and the controller would match the data in the ajax request to your model.
Upvotes: 3
Reputation: 4207
If I'm not mistaken, you are retrieving the data in your request parameter (username) but not the data you send in the Response Body ({data: 'test'}).
I'm not sure which language you are using on your server (looks like java to me) but check for the documentation/tutorials on how to retrieve data from Response Body, it seems like your controller is currently set to retrieve the data from request parameter, which is why you can retrieve the data in the in data attribute of you Ajax Post.
Give me a shout if you need me to explain further.
Upvotes: 1
Reputation: 1390
You need to match the posted names with your method parameters.
Try making this change in your ajax call
data: JSON.stringify({ value: "test" }),
Upvotes: 3