如何将serializeArray作为json传递给MVC控制器
我有一个表单,我想将数据传递给我的控制器。 这是我正在制作的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。 我在下面尝试过 –
data:JSON.stringify({paramJson:data})
但它不起作用。 该怎么办?
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);
我从上面的答案中得到了一些提示,并且能够构建一个对我来说完美的解决方案。 我现在收到一个格式为formname: formvalue
而不是name: formname, value: formvalue
format的name: formname, value: formvalue
。 这里是 –
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);
好吧,我确实尝试了所有上述解决方案,但对我来说有用的是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); } });
希望能帮到别人。