views:

564

answers:

4

I have a JQuery confirmation popup, with Yes, No buttons. The Yes button calls this function:

   function doStuff() {
            $('#confirmPopup').dialog("close");
            var someKey = $("#someKey")[0].value;
            $.post("/MYController/MyAction", { someKey : someKey },
           function(responseText, textStatus, XMLHttpRequest) {

            });
            return false;
        }

This successfully calls my controller action(2 different attempts):

 public ActionResult MyAction(int someKey)
 {
     //do stuff
     return RedirectToAction("OtherAct", "OtherCont");
}



 public JavaScriptResult MyAction(int someKey)
     {
         //do stuff
         return JavaScript("Window.location.href='OtherCont/OtherAct';");
    }

In both cases the action gets executed, but re-direct to the other action does not occure. why?

A: 

I have seen issues with Web Service redirect calls where they won't work this way.

Another approach is to send the url you want to redirect to back to the client, then use Javascript to do the redirect (Window.location.href = ....)

Or, just do an HTML Submit instead of a web service call.

Chris Brandsma
+1  A: 

Because you cannot redirect from an action which is invoked asynchronously ($.post). Look here for alternative.

Darin Dimitrov
A: 

Because you're using ajax, which means a redirect from the action will be ignored.

A solution to have the redirect invoke could be to create another helper that uses a normal FORM POST and no ajax.. then the whole page will POST and the action will redirect.

Here's part of my helper that does exactly that:

        string deleteLink = String.Format(@"<a onclick=""deleteRecord({0})"" href='#'>Delete</a><form id='deleteForm' method='post' action='" +
             routeRelativePath + "/" + actionPrefix + "Delete/" + model.ID +
            @"'></form>", model.ID);

.. more on the above.

cottsak
A: 

OtherAct on OtherContController ... is it decorated with [AcceptVerbs(HttpVerbs.Post)]?

If so, there's the first of your problems. Your action that returns a JavaScriptResult will work. But if the action is decorated with an HttpVerbs.Post, then there is no Get action for that and the Ajax call is getting a 404 not found. Of course, since it is happening asynchronously, you'd have no way of knowing that. No error messages would be displayed.

The second problem is easier. You said ...

return JavaScript("Window.location.href='OtherCont/OtherAct';")

... when what you meant was ...

return JavaScript("window.location.href='OtherCont/OtherAct';")

... or more properly ...

return JavaScript("window.location.href='" + 
       Url.Action("OtherAct", "OtherCont") + "';");

That should get you there.

Rap