views:

48

answers:

2

I would like to redirect to another page within an action method when for instance a certain exception occurs or authorization fails. This is not a problem with normal requests, however when the request is made via Ajax, redirection fails. Many folks out there seem to suggest that I should send back a JavaScriptResult and change the document.location, but I'm not sure if this is the best solution. Are there any alternative ways to achieve this? Thanks.

P.S. I am using ASP.NET MVC v1.0.

+3  A: 

The only way to do a "redirect" via AJAX is with javascript, whether you pass back a JavaScriptResult with a script that sets the location or the new URL in JSON and set the location in the callback handler. I think the choice really depends on how you would handle the result of the request otherwise. If it's always going to redirect, I would simply make the request without AJAX. If normally, you'd return HTML that gets put on the page, then a JavaScriptResult may be better. If you're typically getting JSON and updating the page via code, then I'd send back a JSON response containing the URL and let the callback handler set the location.

tvanfosson
Thanks. The JavaScriptResult option seems to be a sort of hack, so I'll go with the JSON option, which looks clearer.
A: 

I was trying to do the same and this url was a big help for me. I modified it slightly so that it would work with RedirectResult as well as just Redirect.

http://craftycodeblog.com/2010/05/15/asp-net-mvc-ajax-redirect/

Just have all of your Controllers inherit from this base Controller.

 public abstract class MyBaseController : Controller {

            protected override RedirectToRouteResult RedirectToRoute(string routeName, System.Web.Routing.RouteValueDictionary routeValues) {
                return new AjaxAwareRedirectResult(Url, routeName, routeValues);
            }

            public class AjaxAwareRedirectResult : RedirectToRouteResult {
                public AjaxAwareRedirectResult(UrlHelper url, string routeName, System.Web.Routing.RouteValueDictionary routeValues)
                    : base(routeName, routeValues) {
                    this.url = url;
                }

                private readonly UrlHelper url;

                public override void ExecuteResult(ControllerContext context) {
                    if (context.RequestContext.HttpContext.Request.IsAjaxRequest()) {
                        string destinationUrl = url.RouteUrl(base.RouteName, base.RouteValues);
                        JavaScriptResult result = new JavaScriptResult()
                        {
                            Script = "window.location='" + destinationUrl + "';"
                        };
                        result.ExecuteResult(context);
                    } else {
                        base.ExecuteResult(context);
                    }
                }
            }

        }
Evan Schumacher