【发布时间】:2016-11-24 21:53:32
【问题描述】:
我想首先说我已经尝试了关于这个问题的大多数 SO 答案,但他们没有解决这个问题。
通过 jQuery ajax 请求发布到我的控制器操作时遇到问题。
这是我的 JSON 对象:
var service = {
ServiceID: $('#ServiceID').val(),
ServiceName: $('#ServiceName').val(),
ServiceActive: $('#ServiceActive').val(),
ServiceDescriptionShort: $('#ServiceDescriptionShort').val(),
ServiceDescription: $('#ServiceDescription').val()
};
这是我的课:
public class ServiceJson
{
public int ServiceID
{
get;
set;
}
public string ServiceName
{
get;
set;
}
public bool ServiceActive
{
get;
set;
}
public string ServiceDescriptionShort
{
get;
set;
}
public string ServiceDescription
{
get;
set;
}
}
这是我的行动(现在什么都不做,但这不是重点):
[HttpPost]
[Route("edit")]
[ValidateJsonAntiForgeryToken]
public JsonResult Edit(ServiceJson service)
{
return Json("", JsonRequestBehavior.AllowGet);
}
最后,这是我的 ajax 请求:
$.ajax(
{
type: 'POST',
url: '@Url.ActionWithoutData("edit", "service")',
data: JSON.stringify(service),
headers: {
"__RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
contentType: false,
success: function (responseData) {
$('#ServiceID').val(responseData.ServiceID);
$.snackbar({ content: 'Successfully saved.' });
},
error: function (xhr, ajaxOptions, thrownError) {
$('#errorMessage').html(xhr.responseJSON.Message);
$('#error').modal('toggle');
}
});
我的问题是这个 JSON 对象没有序列化到我的类中。显然名称对应。我确信我错过了一些微不足道的东西,因为我尝试使用简单的参数,比如只传递名称(当然还有更改动作参数以对应它),但没有运气。我可以在 Request 对象中看到我正在接收我的数据,但它没有被反序列化为我的对象。
在浏览器中我也可以看到对象被正确传递了。
救命!
【问题讨论】:
-
只需
data: service,并删除contentType: 'application/json; charset=utf-8',、processData: false,和contentType: false, -
关于你的action参数ServiceJson服务为null?
-
ActionWithoutData to Action?
标签: jquery json ajax asp.net-mvc post