I'm just trying to pass a simple object to an MVC controller method without having to create a view model for it. The parameter in the controller method is always null though it id getting called. My jquery post is below.
$(function () {
$("button[id$='addidentifier']").click(function (evt) {
alert('button click');
evt.preventDefault();
var postdata = {
identifier: $('#Identifier').val(),
goldkey: $('#Goldkey').val()
};
$.ajax({
type: 'POST',
url: 'altbloomberg/AddIdentifier',
data: JSON.stringify({ postdata : postdata }) ,
success: function(data) {
alert('data: ' + data);
},
failure: function(a,b,c) {
alert(a);
},
//contentType: "application/json",
dataType: 'json'//,
//processData: false
});
});
the controller method is simple enough, I don't even have the body of it done cause I wanted to get the data passing in first.
[System.Web.Http.HttpPost]
public ActionResult AddIdentifier(string postdata)
{
// put here to place a breakpoint to look at postdata
string lookhere = "";
}
I've looked at other post and this is what they "seem" to indicate to do. This seems like it should be easy enough. So what am I doing wrong here?
Per some suggestions below: I changed the jquery function to pass
$.ajax({
type: 'POST',
url: 'altbloomberg/AddIdentifier',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(postdata),
success: function(data) {
alert('data: ' + data);
},
failure: function(a,b,c) {
alert(a);
}
});
I just changed the stringify method params and set the content type, then changed the controller params to
(string identifier, string goldkey).
This works as the results of the stringify method are
"{"identifier":"XS0939678792","goldkey":"LAW"}"
So why is it then if I just use ONE param in the controller method
(String postdata)
and use
JSON.Stringify({postdata:postdata})
the results of which are
"{"postdata":{"identifier":"XS0939678792","goldkey":"GOVT"}}" does it NOT work.
Shouldn't the controller method match on the postdata json value?