I am trying to perform some operation on button click and after that it should redirect to another action. But it is not working and it returns control back to view.
JavaScript code
document.getElementById('newform').onsubmit = function ()
{
var model = new FormData();
model.append("ID", '@Model.ID');
$.ajax({
url: "/Workflow/UpdateStatus",
type: "POST",
data: model,
contentType: false,
processData: false,
success: function (response) {
if(!response.success)
{
alert("here1");
}
},
error: function (xhr, error, thrown) {
alert("here2" + xhr.responseText);
}
});
return false;
}
Controller code
[HttpPost]
public ActionResult UpdateStatus(string ID)
{
try
{
//Do_Something_Here;
RedirectToAction("List", "Workflow", new { Id = "U" + ID });
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = ex.Message,
});
}
}
If I write RedirectToAction without return in controller then it says that not all codes paths return a value. If I use return RedirectToAction then instead of redirecting it goes back to JavaScript and prints on screen here1
Why is it not redirecting?
Well, as you are submiting ajax request which always expect a response and execute either of
successorerrorthis is why you are getting thealert("here1");because requestreturn 200 success code. Altough it redirected toList actionas its ajax request in client-side it always execute the success function.Solution:
You have two way to handle this scenario and redirect to your desired action.
Way:1
Keeping the Ajax pattern: In this scenario, you have to return json just like below:
Controller:
View: Script:
Output:
Way:2
Asp.net core
form submitController:
Output:
Either of the way would resolve your issue as expected.