我试图找到问题的解决方案。
在视图中:
var postData = [{ "MissionSheetMasterId": MS_MasIds, "EmployeeId": EmpIds, "PaidQty": Qtys, "PaidAmount": Amount }];
console.log(postData);
$.ajax({
url: '@Url.Action("AddEmpToDetails", "Home")',
contentType: "application/json",
async : true,
data: JSON.stringify(postData),
dataType: "json",
type: "POST"
});
<我的控制器中的
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddEmpToDetails([DataSourceRequest]DataSourceRequest request, IEnumerable<MissionSheetDetail> missionsheetdetails)
{
var entities = new List<MissionSheetDetail>();
if (missionsheetdetails != null && ModelState.IsValid)
{
foreach (var missionSheetDetail in missionsheetdetails)
{
var entity = new MissionSheetDetail
{
MissionSheetDetailId = missionSheetDetail.MissionSheetDetailId,
MissionSheetMasterId = missionSheetDetail.MissionSheetMasterId,
EmployeeId = missionSheetDetail.EmployeeId,
PaidQty = missionSheetDetail.PaidQty,
PaidAmount = missionSheetDetail.PaidAmount
};
db.MissionSheetDetails.Add(entity);
entities.Add(entity);
}
db.SaveChanges();
}
return Json(entities.ToDataSourceResult(request, ModelState));
}
这是我的chrome控制台截图:
所以,请检查我的代码并告诉我有什么东西我缺少或我的代码完全错误。
答案 0 :(得分:0)
您发送的数据类型与.NET对象之间似乎存在一些不一致。例如,您发送的EmployeeId
属性是一个字符串数组,但您的.NET属性只是一个整数:
public int EmployeeId { get; set; }
因此,请确保您发送的内容与您希望收到的内容保持一致。所以要么更新你的.NET模型:
public string[] EmployeeId { get; set; }
或将您从客户端发送的数据固定为单个整数值而不是数组。
您的其他媒体资源也是如此:MissionSheetMasterId
,PaidAmound
,...
我认为您传递的javascript变量包含数组而不是单个值,因此请解决这些问题:
var postData = [{
"MissionSheetMasterId": 123,
"EmployeeId": 456,
"PaidQty": 789,
"PaidAmount": 10
}];
因此,您可以修复要发送的JSON数据,以便每个id元素都有一个视图模型。因此,假设您的MS_MasIds
,EmpIds
,Qtys
和Amount
javascript数组变量包含相同数量的元素,您可以这样做:
var postData = [];
if (MS_MasIds.length != EmpIds.length ||
MS_MasIds.length != Qtys.length ||
MS_MasIds.length != Amount.length) {
alert('Sorry you have inconsistency in your data');
} else {
for (var i = 0; i < MS_MasIds.length; i++) {
postData.push({
MissionSheetMasterId: MS_MasIds[i],
EmployeeId: EmpIds[i],
PaidQty: Qtys[i],
PaidAmount: Amount[i]
});
}
$.ajax({
url: '@Url.Action("AddEmpToDetails", "Home")',
contentType: "application/json",
data: JSON.stringify(postData),
type: "POST"
});
}