Home > Back-end >  How to redirect the JSON object in ASP.NET core with ADO.NET
How to redirect the JSON object in ASP.NET core with ADO.NET

Time:02-01

In my project I have displayed pop-ups in create, edit and delete. After I am clicking the create button enter the details and then submit, the page doesn't redirect to the index page. But data is updated. Why this errors. I was used jquery AJAX post submission. When I was clicking the events it does't redirect to the index view page.

In below my BookController Http Post action method What is the mistake in this code.

BookController:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddOrEdit(int id, [Bind("BookID,Title,Author,Price")] BookViewModel bookViewModel)
{
    if (ModelState.IsValid)
    {
        //Sql Connection
        using (SqlConnection sqlConnection = new SqlConnection(_configuration.GetConnectionString("BookConnection")))
        {
            sqlConnection.Open();
            SqlCommand sqlCmd = new SqlCommand("BookAddOrEdit", sqlConnection);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("BookID", bookViewModel.BookID);
            sqlCmd.Parameters.AddWithValue("Title", bookViewModel.Title);
            sqlCmd.Parameters.AddWithValue("Author", bookViewModel.Author);
            sqlCmd.Parameters.AddWithValue("Price", bookViewModel.Price);
            sqlCmd.ExecuteNonQuery();
        }
        **return RedirectToAction(nameof(Index));
        //return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this,         "Index") });**
    }
    return Json(new {isValid= false,html = Helper.RenderRazorViewToString(this,"AddOrEdit",   bookViewModel) });
}

CodePudding user response:

When you use ajax, you cannot use RedirectToAction to redirect to the index page.

You can change your return method like below:

return Json(new { redirectToUrl = Url.Action("Index", "Book") });

And add Success in Ajax like:

success: function (response) {
                window.location.href = response.redirectToUrl;
            }
  • Related