【发布时间】:2021-12-10 04:50:10
【问题描述】:
我正在使用 Ajax 发布我的数据,数据已成功发布到数据库。但我没有从Create 方法得到回复。
我的意思是返回 RedirectToAction("Index"); 页面没有重定向到索引页面。
// POST: TestModels/Create
[HttpPost]
public ActionResult Create(TestModel testModel)
{
if (ModelState.IsValid)
{
db.TestModels.Add(testModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(testModel);
}
另外,我试过了:
// POST: TestModels/Create
[HttpPost]
public JsonResult Create(TestModel testModel)
{
if (ModelState.IsValid)
{
db.TestModels.Add(testModel);
db.SaveChanges();
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = false, responseText = "Error." }, JsonRequestBehavior.AllowGet);
}
我仍然没有收到任何Json 回复。
我的javascript函数::
<script>
$(document).ready(function () {
$('#btn_submit').click(function () {
var testModel = {
FirstName: $('#FirstName').val(),
LastName: $('#LastName').val(),
Gender: $("input[name='Gender']:checked").val(),
Contact: $('#Contact').val(),
Faculty: $('#Faculty').val(),
RegNepaliDate: $('#RegNepaliDate').val()
};
alert(JSON.stringify(testModel));
$.ajax({
type: "POST",
url: "/TestModels/Create",
data: JSON.stringify(testModel),
contentType: "application/json;charset=utf-8",
dataType: 'json',
success: function (response) {
console.log(response);
if (response.success) {
console.log(response.responseText);
console.log(data);
}
},
error: function (response) {
alert("failed...");
}
})
})
})
</script>
数据被发布到服务器,当我浏览Index 页面时,新插入的数据也会显示出来。
另外,当我点击Create页面的提交按钮时,表单数据变得清晰,但所有数据都显示在url栏中
https://localhost:44399/TestModels/Create?FirstName=machhi&LastName=go&Gender=male&Contact=5589512369&Faculty=science&RegNepaliDate=2021-05-01
【问题讨论】:
-
在 Chrome 中,按 F12 并切换到网络选项卡并监视发布请求?它是否返回 200 状态码?
-
你也可以给你看一下吗?
-
@Greg 在使用 firefox 开发工具进行调试时,在 Network -> POST 方法中显示 NS_BINDING_ABORTED 在
Transferred选项卡中。 -
NS_BINDING_ABORTED 可能是 Firefox 特定的问题。看看stackoverflow.com/questions/704561/…。我建议使用 Chrome 调试您的代码,以找出 POST 请求的响应
标签: javascript asp.net asp.net-mvc asp.net-mvc-4 asp.net-ajax