我正在使用 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
uj5u.com熱心網友回復:
您能否添加缺少的 jQuery 庫檔案,例如“
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery-3.4.1.slim.min.js"></script>
" 以獲取 Controller 的回應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363057.html
