Home > other >  JQuery ajax call blocks RedirectToAction
JQuery ajax call blocks RedirectToAction

Time:09-16

I have a view with an ajax call:

 $.ajax({
            url: "CreateChecklistCopies",
            type: "POST",
            data: JSON.stringify(drivers),
            async: false,
            contentType: "application/json; charset=utf-8",            
        });

The controller action performs some tasks and redirects to the index method of the controller:

        [HttpPost]
        public IActionResult CreateChecklistCopies([FromBody] object i_vm)
        {
            var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
            int result = _obj.AddChecklistCopies(tmp);
            
            if (result > 0)
                return RedirectToAction("Index", new { SuccessMessage = "Checklists were successfully duplicated." });            
            else 
                return RedirectToAction("Index", new { ErrorMessage = "An error occurred when duplicating the checklist." });            
        }

The Index action is successfully executed but there's no forward to the index page happening:

[HttpGet]
        public IActionResult Index(string FilterCreator, string salesPersonFilter, string SuccessMessage, string ErrorMessage)
        {
            if (FilterCreator == null)
            {
                FilterCreator = User.Identity.Name.Split("\\")[1];
            }
            else if (FilterCreator.ToLower() == "all")
            {
                FilterCreator = null;
            }

            var checklists = _obj.GetChecklists(true, FilterCreator, salesPersonFilter);
            var salespersons = _obj.GetSalespersons();
            var chlVm = _mapper.Map<List<ChecklistModel>, List<ChecklistListViewModel>>(checklists);
            var ivm = new IndexViewModel
            {
                CheckLists = chlVm,
                Salespersons = salespersons,
                SuccessMessage = !string.IsNullOrEmpty(SuccessMessage) ? SuccessMessage : "",
                ErrorMessage = !string.IsNullOrEmpty(ErrorMessage) ? ErrorMessage  : ""
            };

            return View(ivm);
        }

I played around with the async: false tag in the ajax call but that didn't help. Any ideas?

CodePudding user response:

You cannot use RedirectToAction to action in an ajax call to redirect the entire page. Because the ajax response is limited to the ajax request scope only.

What you can do is return a json object instead of RedirectToAction like this:

[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
    var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
    int result = _obj.AddChecklistCopies(tmp);
    
    JsonResult result = new JsonResult(new JsonSerializerSettings());

    if (result > 0)
        result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "Checklists were successfully duplicated." });            
    else
        result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "An error occurred when duplicating the checklist." });

    return result;
}

Then in the ajax call do this:

$.ajax({
    url: "CreateChecklistCopies",
    type: "POST",
    data: JSON.stringify(drivers),
    dataType: 'JSON',
    async: false,   
}).done(function (response) {
    
    if (response != null) {
        
        window.location = response.RedirectUrl;
        
        //You can also use the IsRedirect  and SuccessMessage property as needed
        
    } else {
        alert('There was a problem processing the request.');
    }
}).fail(function () {
    alert('There was a problem processing the request.');
});
  • Related