我无法将 HTTP POST 请求正文中传入的 JSON 数据绑定(bind)到我的 C# 模型。
这是我的前端 JavaScript 代码:
let jsonData = "{\"Updates\":[{\"CarrierStateMapGuid\":\"de4abaa8-42d2-4e00-657a08d5577ac94a\",\"QuestionTag\":\"CoQstPAVT500006\",\"MemberOf\":\"Quote\",\"Condition\":\"0\",\"QuestionType\":\"List\",\"TrueAnswer\":\"NoDiscount\",\"TrueExplanation\":\"No Discount\",\"FalseAnswer\":null,\"FalseExplanation\":null,\"DeleteRequest\":false}]}";
$.ajax({
url: "/api/CarrierQuestionMappingApi/UpdateQuestionMaps",
type: "POST",
contentType: "application/json; charset=utf-8",
data: jsonData
});
这是我的 C# 模型:
public class UpdateCarrierQuestionMapsWebRequests
{
public UpdateCarrierQuestionMapsWebRequest[] Updates { get; set; }
public class UpdateCarrierQuestionMapsWebRequest
{
public string CarrierStateMapGuid { get; set; }
public string QuestionTag { get; set; }
public string MemberOf { get; set; }
public string Condition { get; set; }
public string QuestionType { get; set; }
public string TrueAnswer { get; set; }
public string TrueExplanation { get; set; }
public string FalseAnswer { get; set; }
public string FalseExplanation { get; set; }
public bool DeleteRequest { get; set; }
}
}
这是我的后端 C# Controller 代码:
[HttpPost]
[Route("api/[controller]/UpdateQuestionMaps")]
public HttpResponseMessage UpdateQuestionMaps(UpdateCarrierQuestionMapsWebRequests request)
{
// request.Updates is null
}
我不明白为什么 request.Updates 为 null 并且没有被模型绑定(bind)器设置。
最佳答案
该问题与 AJAX 和 ASP.NET MVC 有关。 MVC 不喜欢来自 AJAX 的任何序列化。当您向 AJAX 传递一个对象时,它会手动对其进行序列化,而 MVC 期望以 AJAX 对其进行序列化的方式对其进行反序列化。所以任何手动序列化都会破坏这个过程。在上面的方法中,您将得到一个编码字符串。但是,如果您将 AJAX 调用更改为:
let jsonData = "[{\"CarrierStateMapGuid\":\"de4abaa8-42d2-4e00-657a08d5577ac94a\",\"QuestionTag\":\"CoQstPAVT500006\",\"MemberOf\":\"Quote\",\"Condition\":\"0\",\"QuestionType\":\"List\",\"TrueAnswer\":\"NoDiscount\",\"TrueExplanation\":\"No Discount\",\"FalseAnswer\":null,\"FalseExplanation\":null,\"DeleteRequest\":false}]";
$.ajax({
url: "/api/CarrierQuestionMappingApi/UpdateQuestionMaps",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
Updates: jsonData
}
});
数据将作为表单数据发送并在 Controller 上正确序列化。
关于javascript - ASP.NET MVC 5 - 模型绑定(bind)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48175474/