我正在开发一个 ASP.net MVC 4 应用程序,在其中一个页面中我有一个表单,我正在遍历所有输入并将其转换为 json 数据。
使用 fiddler、chrome 开发工具和 firebug,我已验证数据已正确转换为 json。我正在使用 $ajax 将数据发布到 mvc Controller ,但每次我都会收到错误消息。
我似乎无法弄清楚为什么它不起作用。我敢打赌,如果我能弄清楚如何获取错误消息,我就能弄清楚如何让它工作。当我尝试在控制台中查看时,我没有看到错误消息。我试过将错误消息记录到控制台,但它没有显示任何内容。
如果有人能帮我弄清楚如何获取错误消息,我将不胜感激。我还会发布代码,以防遗漏一些明显的东西。
这是我的javascript代码:
$(function () {
$("#saveform").submit(function () {
var myRows = [];
var $headers = $("th");
var $rows = $("tbody tr").each(function (i, n) {
var $row = $(n);
myRows.push({
id: $row.find('#item_SpecimenId').val(),
site: $row.find('#item_Site').val(),
clinicalImpression: $row.find('#item_ClinicalImpression').val(),
degreeOfSuspicion: $row.find('#item_DegreeOfSuspicion').val(),
margins: $row.find('#item_Margins :selected').text(),
count: $row.find('#item_Count').val(),
lesionSize: $row.find('#item_LesionSize').val(),
});
});
var specimens = JSON.stringify(myRows);
var url = '/PathSlip/DoctorSlip';
$.ajax({
url: url,
data: '{ id:1, post:2 }',
type: 'POST',
dataType: 'json',
statusCode: {
404: function () {
$("#response").html('Could not contact server.');
},
500: function () {
$("#response").html('A server-side error has occurred.');
}
},
success: function () {
$("#response").html('success');
},
error: function (xhr, ajaxOptions, thrownError) {
$("#response").html('an error');
}
});
});
});
这是我在 Controller 中使用的 viewModel
public class SpecimenViewModel
{
public int id { get; set; }
public string site { get; set; }
public string clinicalImpression { get; set; }
public string degreeOfSuspicion { get; set; }
public string margins { get; set; }
public string count { get; set; }
public string lesionSize { get; set; }
}
这是我的 mvc Controller
public ActionResult DoctorSlip(int id)
{
var specimens = _repo.GetSpecimensByBiopsyId(id).ToList();
return View(specimens);
}
[HttpPost]
public ActionResult DoctorSlip(IEnumerable<SpecimenViewModel> specimens)
{
return RedirectToAction("DoctorSlip");
}
非常感谢对此的任何帮助。
最佳答案
当我使用 $.post
而不是 $.ajax
时,它起作用了,但我不知道为什么。
关于c# - Asp.net MVC 4 Ajax 发布请求不起作用,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366108/