首页 > 解决方案 > Ajax:从 asp.net mvc 中的数据库中删除记录而不重新加载页面

问题描述

我正在尝试删除移动表单数据库,即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");
        });
    }

我的问题在上面的代码中。单击删除按钮后,我永远不想重新加载页面。 MobileController.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");
        }

有人请建议我,我该怎么办?

标签: c#asp.net-mvcasp.net-ajax

解决方案


我已经解决了我的问题。通过在我的案例中添加一些代码行。正如你在下面看到的。

$(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");
        });
    }

推荐阅读