使用ajax从数据库Mvc中的表中删除行

时间:2016-04-06 11:33:07

标签: javascript asp.net-mvc asp.net-ajax

我想使用ajax从数据库中删除行,并在删除后刷新包含所有数据的部分视图

<a class="fa fa-times" href="javascript:DeleteCurrency(@item.CountryID)" title="Delete"></a>

**这是调用javascript函数**的锚链接

 function DeleteCurrency(CountryID) {
        var Con = confirm("are you sure ?");
        if (Con == true) {
            $.ajax({
                url: "@Url.Action("DeleteCountry","Main")" + CountryID,
                type: 'Delete',
                async: true,
                processData: false,
                cache: false,
                sucess: function (data) {
                    alert(dtat);
                },

                error: function (xhr) {
                    alert('error');

                }


            });
        }

    }

**这是我的删除控制器方法**

 [HttpDelete]
    public ActionResult DeleteCountry(int CountryID)
    {
        try
        {
            Country count = db.Countrys.Find(CountryID);
            db.Countrys.Remove(count);
            db.SaveChanges();
            var AllCountries = (from cur in db.Countrys orderby cur.govCode ascending select cur).ToList();
            ViewBag.Count = (from cur in db.Countrys orderby cur.govCode ascending select cur).ToList().Count();
            return PartialView("_DetailsOfData", AllCountries);
        }
        catch (Exception)
        {
            ViewBag.AlreadyAdded = "يوجد محافظات تابعه لهذه الدوله لا يمكن مسحها";
            var AllCountries = (from cur in db.Countrys orderby cur.govCode ascending select cur).ToList();
            ViewBag.Count = (from cur in db.Countrys orderby cur.govCode ascending select cur).ToList().Count();
            return View("AddCountry", AllCountries);
        }
    }

当我点击锚链接确认消息弹出窗口(你确定吗?)当点击确定时它一直输入错误我想知道什么是错误

1 个答案:

答案 0 :(得分:0)

CountryID应该在ajax数据属性中单独传递。例如:

    function DeleteCurrency(CountryID) {
            var Con = confirm("are you sure ?");
            if (Con == true) {
                $.ajax({
                    url: "@Url.Action("DeleteCountry","Main")" ,
                    type: 'Delete',
                    data: {
                        CountryID: CountryID,
                    },
                    dataType: "text/html",
                    async: true,
                    cache: false,
                    sucess: function (data) {
                        alert(dtat);
                    },

                    error: function (xhr) {
                        alert('error');

                    }


                });
            }

        }