我正在尝试使用jquery向Web API控制器发布http帖子,我正在将对象数组发布到控制器,但是当到达服务器时,该数组为空。
javascript
var url = "api/actuary/" + $("#ActuaryId").val() + "/documents/";
var inputs = $("#proofOfTraining input[type='checkbox']");
var courseAttended = []
inputs.each(function (ind, val) {
var course = {};
course["IsDone"] = $(val).is(":checked");
course["Title"] = $(val).attr("name");
course["ActuaryId"] = $("#ActuaryId").val();
courseAttended.push(course);
});
console.log(courseAttended)
$.post(url, JSON.stringify({ courseAttended }), function (response) {
console.log(response)
})
发布数据
控制器
[Route("api/actuary/{actuaryId:long}/documents/")]
[HttpPost]
public async Task<IHttpActionResult> uploadCourseTrainingProofAsync(List<CourseModel> courseAttended)
{
try
{
using (Data.ADPDB db = new Data.ADPDB())
{
foreach (CourseModel course in courseAttended)
{
var tempDoc = new documents();
tempDoc.ActuaryId = course.ActuaryId;
tempDoc.Document = null;
tempDoc.DocumentTypeId = -1;
tempDoc.Done = course.IsDone;
tempDoc.Title = course.Title;
db.documents.Add(tempDoc);
}
await db.SaveChangesAsync();
}
return Ok();
}
catch (Exception ex) {
return InternalServerError(ex.InnerException);
}
}
型号
public class CourseModel
{
public int ActuaryId { get; set; }
public string Title { get; set; }
public bool IsDone { get; set; }
}
答案 0 :(得分:1)
这才是对我有用的东西。
JavaScript
var inputs = $("#proofOfTraining input[type='checkbox']");
var courseAttended = []
inputs.each(function (ind, val) {
var course = {};
course["IsDone"] = $(val).is(":checked");
course["Title"] = $(val).attr("name");
course["ActuaryId"] = parseInt($("#ActuaryId").val());
courseAttended.push(course);
});
$.ajax({
url: "api/actuary/" + $("#ActuaryId").val() + "/documents/",
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(courseAttended),
dataType: "json",
success: function (data) {
console.log(data)
}
})
控制器:
[Route("api/actuary/{actuaryId:long}/documents/")]
[HttpPost]
public async Task<IHttpActionResult>
uploadCourseTrainingProofAsync(List<CourseModel> courseAttended)
{
//.....
}
我对为什么要在ajax请求中指定其余详细信息更加感兴趣。
感谢您的建议。
答案 1 :(得分:0)
您已为请求指定Content-Type。为您的情况json。另外,您还必须在模型类中将ActuaryId int的类型更改为字符串。下面是工作代码。
$.ajax({
type: "POST",
contentType: 'application/json',
url: "api/url",
data: JSON.stringify(courseAttended),
success: (response)=> {
console.log(response);
},
error: (response) =>{
console.log(response);
}
});
public class CourseModel
{
public string ActuaryId { get; set; }
public string Title { get; set; }
public bool IsDone { get; set; }
}