'Refreshing Page After Delete With Ajax in ASP.NET MVC

I'm trying to refresh the page after I delete a record from the database. I managed to hack the behaviour I want by reloading the windows inside the ajax 'error' but I'm not quite sure why I can't return success to ajax from my controller.

I've tried the following: Different return types in the controller (RedirectToRoute, RedirectToAction("Index"), Action Result (Return Ok()), plus using POST and GET as the AJAX type (and changing the controller accordingly).

Everything I do (other than reloading inside the error block) deleted the record from the db but never refreshes the page with the new table.

View:

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

Controller

 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();



Solution 1:[1]

when you are using ajax redirect inside of the controller action is not working. Try this

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge