我正在尝试使用ajax将对象从视图传递到控制器。但我在控制器中的对象内获取空值。我的代码如下所示。你能帮我解决一下这个问题吗
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
function Save() {
// var Trip={output};
debugger;
var stop;
var table = $('#scheduletable').DataTable();
var rows = $('#scheduletable tr');
var StopNames = '';
var TripNumbers = '';
var TripDetails = '';
StopNames += table.column(0).data().toArray().join("&");
for (var i = 1; i < rows[0].cells.length; i++) {
TripNumbers += rows[0].cells[i].innerText + '&';
TripDetails += table.column(i).data().toArray().join("&");
}
debugger;
TripNumbers = TripNumbers.replace(/(\r\n|\n|\r)/gm, "");
var output = {
'StopNames': StopNames,
'TripNumbers': TripNumbers,
'TripDetails': TripDetails
};
$.ajax({
type: "POST",
url: "/ScheduleManagement/ScheduleManagement/SaveSchedules",
// contentType: 'application/json;',
dataType: "json",
data: JSON.stringify(output),
success: function (values) {
},
error: function (err) {
console.log(err);
}
});
}
我在控制器中使用以下代码
[HttpPost]
public JsonResult SaveSchedules(TripsToSave output)
{
// dynamic item = output;
int serviceId = Convert.ToInt32(Session["ServiceGroupId"]);
// int status= _scheduleManagementBL.SaveMasterSchedule(output);
return Json("1", JsonRequestBehavior.AllowGet);
// return RedirectToAction("DisplayHttpError", "Error");
}
我在此代码中使用的实体是
public class TripsToSave
{
public string StopNames { get; set; }
public string TripNumbers { get; set; }
public string TripDetails { get; set; }
}
答案 0 :(得分:1)
你可以试试这个
var output = {
StopNames: 'StopNames', // change the value with string
TripNumbers: 'TripNumbers', // change the value with string
TripDetails: 'TripDetails' // change the value with string
};
$.ajax({
type: "POST",
url: "/ScheduleManagement/ScheduleManagement/SaveSchedules",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(output),
success: function (values) {
},
error: function (err) {
console.log(err);
}
});
dataType:'json',
来自服务器的平均返回数据类型应为json
contentType:'application / json;字符集= UTF-8' ,
它的平均数据类型应该是json之前将它发送到服务器,在你需要将你的数据转换成json stringfy ..
注意:
弃用通知:从jQuery 3.0开始,jqXHR.success(),jqXHR.error()和jqXHR.complete()回调被删除。您可以使用jqXHR.done(),jqXHR.fail()和jqXHR.always()代替更多detial请访问 - 访问
答案 1 :(得分:0)
你不需要对输出数据进行字符串化,传递就是这样。
var StopNames = 'ss';
var TripNumbers = 'ss';
var TripDetails = 'cc';
var output = {
'StopNames': StopNames,
'TripNumbers': TripNumbers,
'TripDetails': TripDetails
};
$.ajax({
type: "POST",
url: "/abc/SaveSchedules",
dataType: "json",
data: output,
success: function (values) {
},
error: function (err) {
console.log(err);
}
});