views:

1507

answers:

2

I am using the Ajax.BeginForm to create a form the will do an ajax postback to a certain controller action and then if the action is successful, the user should get redirected to another page (if the action fails then a status message gets displayed using the AjaxOptions UpdateTargetId).

using (Ajax.BeginForm("Delete", null,
        new { userId = Model.UserId },
        new AjaxOptions { UpdateTargetId = "UserForm", LoadingElementId = "DeletingDiv" },
        new { name = "DeleteForm", id = "DeleteForm" }))
   {
    [HTML DELETE BUTTON]
   }

If the delete is successful I am returning a Redirect result:

[Authorize]
public ActionResult Delete(Int32 UserId)
{
    UserRepository.DeleteUser(UserId);
    return Redirect(Url.Action("Index", "Home"));
}

But the Home Controller Index view is getting loaded into the UpdateTargetId and therefore I end up with a page within a page. Two things I am thinking about:

  1. Either I am architecting this wrong and should handle this type of action differently (not using ajax).
  2. Instead of returning a Redirect result, return a view which has javascript in it that does the redirect on the client side.

Does anyone have comments on #1? Or if #2 is a good solution, what would the "redirect javascript view" look like?

+1  A: 

The behavior you're trying to produce is not really best done using AJAX. AJAX would be best used if you wanted to only update a portion of the page, not completely redirect to some other page. That defeats the whole purpose of AJAX really.

I would suggest to just not use AJAX with the behavior you're describing.

Alternatively, you could try using jquery Ajax, which would submit the request and then you specify a callback when the request completes. In the callback you could determine if it failed or succeeded, and redirect to another page on success. I've found jquery Ajax to be much easier to use, especially since I'm already using the library for other things anyway.

You can find documentation about jquery ajax here, but the syntax is as follows:

jQuery.ajax( options )  

jQuery.get( url, data, callback, type)

jQuery.getJSON( url, data, callback )

jQuery.getScript( url, callback )

jQuery.post( url, data, callback, type)
Joseph
So then just do a regular POST to the Delete action and in most cases it will succeed and then I can redirect to the Home Index page. In the cases where it would fail, then display a different view with the error messages and the appropriate action for the user to take. Sound ok?
Jeff Widmer
Yeah that sounds like it would make more sense.
Joseph
I went ahead with converting this from an Ajax submit to a regular POST as per Joseph's recommendation. This actually worked out better since it gave me a cleaner way to handle the delete confirmation messaging.
Jeff Widmer
A: 

This should do the trick: http://craftycodeblog.com/2010/05/15/asp-net-mvc-ajax-redirect/

Kevin Craft