[英]Ajax : Delete record from database in asp.net mvc without reload the page
我正在嘗試刪除移動表單數據庫,即ASP.NET MVC 中的MS SQL Server 。 我在Ajax的幫助下成功地做到了。 但是我需要重新加載頁面,然后它會顯示正確的結果。
索引.cshtml
$(function () {
$(".DeleteMobile").click(function () {
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Mobile/DeleteMobile/" + DeleteId,
type: "Post"
}).done(function () {
getAllMobiles();
}).error(function () {
alert("Something Went Wrong.");
});
});
});
function getAllMobiles() {
$.ajax({
url: "/Mobile/Index",
type: "Get"
}).done(function () {
alert("All Mobiles get");
});
}
我的問題出在上面的代碼中。 單擊刪除按鈕后,我不想重新加載頁面。 移動控制器.cs
public ActionResult Index()
{
MobileHandler mh = new MobileHandler();
List<Mobile> Mobiles = mh.GetMobiles();
return View(Mobiles);
}
public ActionResult DeleteMobile(int id)
{
MobileHandler mh = new MobileHandler();
mh.DeleteMobile(id);
return RedirectToAction("Index");
}
任何人請建議我,我該怎么辦?
我已經解決了我的問題。 通過在我的情況下添加一些代碼行。 正如你在下面看到的。
$(function () {
$(".DeleteMobile").click(function () {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Mobile/DeleteMobile/" + DeleteId,
type: "Post"
}).done(function () {
$(button).parents("tr").remove();
}).error(function () {
alert("Something Went Wrong.");
});
});
});
而不是這個代碼
$(function () {
$(".DeleteMobile").click(function () {
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Mobile/DeleteMobile/" + DeleteId,
type: "Post"
}).done(function () {
getAllMobiles();
}).error(function () {
alert("Something Went Wrong.");
});
});
});
function getAllMobiles() {
$.ajax({
url: "/Mobile/Index",
type: "Get"
}).done(function () {
alert("All Mobiles get");
});
}
使用 ajax 調用,您可以使用 json 結果從控制器傳遞數據或結果,您不能重定向到任何其他操作方法,但是您可以通過控制器中的此更改來實現此目的
public JsonResult DeleteMobile(int id = 0)
{
MobileHandler mh = new MobileHandler();
mh.DeleteMobile(id);
// if data is deleted then return true else return false
return Json(true, JsonRequestBehavior.AllowGet);
}
$(function () {
$(".DeleteMobile").click(function () {
var DeleteId = $(this).data("deleteid");
$.ajax({
url: "/Mobile/DeleteMobile/" + DeleteId,
type: "Post"
}).done(function (result) {
if (result == 'True') {
alert('data is deleted successfully');
}
else {
alert('Error Please Try again..');
}
}).error(function () {
alert("Something Went Wrong.");
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.