使用 ASP.NET MVC 中的 Ajax 删除后刷新页面

Refreshing Page After Delete With Ajax in ASP.NET MVC

我在从数据库中删除记录后尝试刷新页面。我设法通过在 ajax 'error' 中重新加载 windows 来破解我想要的行为,但我不太确定为什么我不能 return 成功到 ajax 来自我的控制器。

我试过以下方法: 控制器中的不同 return 类型(RedirectToRoute、RedirectToAction("Index")、Action Result (Return Ok()),加上使用 POST 和 GET 作为 AJAX 类型(并相应地更改控制器)。

我所做的一切(除了在错误块内重新加载)都从数据库中删除了记录,但从未使用新的 table.

刷​​新页面

查看:

@model todo.ViewModels.TodoViewModel

<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
    </tr>
    @foreach (var t in Model.TodoList)
    {
        <tr>
            <td>@t.Id</td>
            <td>@t.Name</td>
            <td><input type="submit" class="btn btn-danger" value="Delete" onClick="deleteTodo(@t.Id)" /></td>
        </tr>
    }
</table>

js:

function deleteTodo(i) 
{

    $.ajax({
        url: 'Todo/Delete',
        type: 'GET',
        dataType: 'json',
        data: {
            id: i
        },
        success: function() {
            alert('success');
        },
        error: function() {
            alert('fail');
            window.location.reload();
        }
    });
}

控制器

 public IActionResult Index()
        {
            var tdlvm = GetAllTodos();
            return View(tdlvm);
        }

        [HttpGet]
        public RedirectToActionResult Delete(int id)
        {
            using (var connection =
                   new SqlConnection("Server=(localdb)\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Todo"))
            {
                using (var tableCmd = connection.CreateCommand())
                {
                    connection.Open();
                    tableCmd.CommandText = $"DELETE from todo WHERE Id = '{id}'";
                    int rowCount = tableCmd.ExecuteNonQuery();
                }
            }

            return RedirectToAction("Index");
        }

        internal TodoViewModel GetAllTodos()
        {
            List<Todo> todoList = new();

当您在控制器操作中使用 ajax 重定向时不起作用。试试这个

 success: function() {
   alert('success');
   window.location.href= "/home/index";
},

您正在尝试从 Controller 重定向,使用 AJAX 并不是最好的做法。 AJAX 用于更新页面的一部分,通常不用于重定向到其他页面。在您的情况下,您可以执行以下操作:

您需要 return Json 从您的 Controller 方法。您可以通过将您的方法定义为 JsonResult 来做到这一点,这将 return Json 到您的 AJAX 调用。

如果有多个 return 类型可能派生自 ActionResult,您也可以使用 ActionResult,例如 ViewResultFileResultJsonResult,等等

由于您正在执行 GET 操作并且 MVC 默认为 DenyGet 以保护您免受涉及 JSON 请求的非常具体的攻击,因此您需要明确允许它。如果它是一个 POST 动作,那么你不需要费心去设置 JsonRequestBehavior.

[HttpGet]
public JsonResult Delete(int id)
{
    int rowCount=0;
    using (var connection =
           new SqlConnection("Server=(localdb)\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Todo"))
    {
        using (var tableCmd = connection.CreateCommand())
        {
            connection.Open();
            tableCmd.CommandText = $"DELETE from todo WHERE Id = '{id}'";
            rowCount = tableCmd.ExecuteNonQuery();
        }
    }

    if(rowCount > 0)
    {
      return Json(new {status="true", msg= "Successfully deleted"}, JsonRequestBehavior.AllowGet);
    }
    else
    {
      return Json(new {status="false", msg= "Could not delete"}, JsonRequestBehavior.AllowGet);
    }
}

你可以在 AJAX 中这样处理:

function deleteTodo(i) 
{

    $.ajax({
        url: 'Todo/Delete',
        type: 'GET',
        dataType: 'json',
        data: {
            id: i
        },
        success: function(data) {
          if(data.status=="true")
          {
            var urlToRedirect= '@Url.Action("Index","Home")';
            window.location.href = urlToRedirect; //Redirect here
          }
          else if(data.status=="false")
          {
            alert(data.msg)
          }
        },
        error: function() {
            alert('fail');
            window.location.reload();
        }
    });
}