Reputation: 4484
I have a form whose data I want to be passed to my controller. This is the JQuery call that I am making -
var data = $form.serializeArray();
var options = {
contentType: "application/json",
url: "/Form/Save",
data: JSON.stringify(data),
type: "post",
datatype: "html",
success: function (result, xhr, status) {
console.log(result);
},
error: function (xhr, status, error) {
// redirect to error page
}
};
$.ajax(options);
And this is how I am recieving this in controller -
public ActionResult Save(string paramJson)
{
// save paramJson
return null;
}
But all I am recieving in Save action is paramJson = null. I tried below as well -
data: JSON.stringify({paramJson: data})
but it didn't work. What should be done here?
Upvotes: 1
Views: 8157
Reputation: 1
well, I did try all of the above solutions but what worked for me is one option "traditional:true" in ajax call. follow the code below;
var Fixtures = [2,3,4]; var UnitViews = [4,3,6,8];
$.ajax({
url: '/RHomes/umbraco/surface/Propertysurface/GetPropertiesBL',
async: false,
type: "GET",
data: {
iServiceId: serviceid, iLocationID: locationid,
iCategoryId: categoryid, iTypeId: propertyTypeid,
idevhold: developmentHold, iminbed: minBedRoom,
imaxbed: maxBedRom, iminPrice: minPrice,
fixtures: Fixtures, imaxPrice: maxPrice,
views: UnitViews
},
dataType: "html",
traditional: true,
contentType: "application/json",
error: function (data) {
alert(data.value);
},
success: function (data, textStatus, jqXHR) {
//alert(criteria + 'success...' + data);
console.log(data);
$("#ResultContainer").empty().append(data);
}
});
Hope that helps somebody.
Upvotes: 0
Reputation: 4484
I took some hint from above answer and was able to frame a solution which works perfectly for me. I am now recieving a json in the format of formname: formvalue
instead of name: formname, value: formvalue
format. Here it is -
var json = {};
// converting to formname:formvalue format
$.each($form.serializeArray(), function (i, field) {
json[field.name] = field.value || '';
});
// stringify the parameter
var data = { paramJson: JSON.stringify(json) };
var options = {
contentType: "application/json",
url: "/Form/Save",
data: JSON.stringify(data),
type: "post",
datatype: "html",
success: function (result, xhr, status) {
console.log(result);
},
error: function (xhr, status, error) {
// redirect to error page
}
};
$.ajax(options);
Upvotes: 3
Reputation: 733
the ajax call has wrong contentType, it should be something like
var data = { paramJson: JSON.stringify($form.serializeArray()) };
var options = {
contentType: "text/plain",
url: "/Form/Save",
data: JSON.stringify(data),
type: "post",
datatype: "html",
success: function (result, xhr, status) {
console.log(result);
},
error: function (xhr, status, error) {
// redirect to error page
}
};
$.ajax(options);
Upvotes: 2