从数据库中删除记录的脚本不起作用

时间:2016-10-06 10:26:13

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

我想删除带有按钮的记录,该按钮位于索引网页上。我用AJAX写下了一些jQuery,但它不起作用。

这是我的控制器方法。当我使用HttpGet Delete方法在另一个页面上生成的表单调用它时,此方法正常工作。

[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(int id)
{
    var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
    var training = _context.Trainings.Where(t => t.UserId == userId).FirstOrDefault(t => t.Id == id);
    if (training != null && ModelState.IsValid)
    {
        _context.Trainings.Remove(training);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View();            
}
$(document).ready(function () {
    $(".js-delete").on("click", function () {
        var button = $(this);
        var trainingId = button.attr;
        if (confirm("Are you sure you want to delete this training?")) {
            $.ajax({ 
                url: "/Training/Delete/" + trainingId,
                type: "POST",
                contentType: "application/json",
                success: function () {
                    alert("ok");
                },
                error: function(){
                    alert("not ok");                        
            }
            });
        }
    });
});
<button data-customer-id="@training.Id" class="btn btn-link js-delete">Usuń</button>

我现在拥有的是:弹出窗口,在确认我的脚本生成错误结果后,在控制台中我的状态为:400,输入:xhr,响应为:

http://localhost:6822/Training/Delete/function%20(%20name,%20value%20)%20%7Breturn%20access(%20this,%20jQuery.attr,%20name,%20value,%20arguments.length%20%3E%201%20);%7D

1 个答案:

答案 0 :(得分:0)

http://localhost:6822/Training/Delete/function%20(%20name,%20value%20)%20%7Breturn%20access(%20this,%20jQuery.attr,%20name,%20value,%20arguments.length%20%3E%201%20);%7D

我认为网址应该是这样的:

http://localhost:6822/Training/Delete/5 (since your action expects int value in parameter.)

您应该调试脚本并查看您在trainingId中获得的内容。

        var button = $(this);
        var trainingId = button.attr;

因为这里你传递参数下面的函数。     功能20%(%20name,%20value%20)%20%7Breturn%20access(%20this,%20jQuery.attr,%20name,%20value,%20arguments.length%20%3E%201%20);%7D < / p>

我认为你应该尝试:

 var trainingId = $(this).attr("data-customer-id")