我有一个表单,我想将数据传递给我的控制器。这是我正在制作的JQuery调用 -
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);
这就是我在控制器中接收它的方式 -
public ActionResult Save(string paramJson)
{
// save paramJson
return null;
}
但我在Save行动中收到的只是paramJson = null。我也在下面尝试过 -
数据:JSON.stringify({paramJson:data})
但它没有用。应该在这做什么?
答案 0 :(得分:2)
ajax调用的contentType错误,应该是
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);
答案 1 :(得分:2)
我从上面的回答中得到了一些提示,并且能够构建一个对我来说完美的解决方案。我现在收到格式为formname: formvalue
而不是name: formname, value: formvalue
格式的json。这是 -
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);
答案 2 :(得分:0)
好吧,我确实尝试了上述所有解决方案,但对我有用的是一种选择"传统:真实"在ajax电话中。请遵循以下代码;
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);
}
});
希望能帮助某人。