MVC - Breaking out of an AJAX POST to a full redirect

You may sometimes find yourself in a situation when working with MVC and AJAX helpers where you want to return different views based on the outcome of the request. For example, I have a page with a list of departments (my index page). From each department, I can got to a Details page. On the details page, there is a delete button for the department. In my scenerio, sometimes I can delete a department, and sometimes I can't - depending on whether or not they are in use. I am using an AJAX actionlink to call my delete function - if I can't delete the department, I will get a message back to the page, if i can I want to redirect the user back to the list of departments as the details page is no longer relevant. My Ajax link looks like this:

<div id ="output"></div>
@Ajax.ActionLink("Delete", "Delete", 
    new { id = Model.DepartmentId }, 
    new AjaxOptions { HttpMethod="POST", UpdateTargetId="output", Confirm= "Are you sure you want to delete this item?" }, 
    new { @class = "btn btn-danger" })

So if the department cannot be deleted, I see the message in my div "output". However if the message is deleted, I redirect back to my list. This is the controller action:

// POST: /Department/Delete/5
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Delete(int id = 0)
{
    if (id != 0)
    {
        // check to see if the department item is associated with an asset assignment
        bool InUseByAssetAssignment = AssetAssignmentService.ValueInUse(x => x.DepartmentId == id);

        if (InUseByAssetAssignment == false)
        {
            DepartmentService.DeleteDepartment(id);
            return RedirectToAction("Search");
        }
        else
        {
            return Content("<p style='color:#f00';>This department cannot be deleted because there are items associated with it.</p>");
        }
    }
    else
    {
        return Content("You must select a Department to delete!");
    }
}

In this instance, my RedircetToAction won't work, as it renders within my "output" div in the existing page. I need to perform the redirect client side so I replace RedirectToAction with

return JavaScript(string.format("window.location = '{0}'", Url.Action("Search")));

This then performs the redirect in javascript instead, and the user is taken back to the list.

 



Tagged: ASP.NET, MVC, AJAX,
Categorised: ASP.NET MVC,
By:
On: