JQuery calling action on the controller (but not redirecting after)

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 triggers the action of my controller (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 is performed, but the redirect to another action does not occur. why?

+4
source share
4 answers

Since you cannot redirect an action that is invoked asynchronously ($ .post). Look here for an alternative.

+3
source

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

If so, that is the first of your problems. Your action returning JavaScriptResult will work. But if the action is decorated with HttpVerbs.Post, then there is no Get action for this, and the Ajax call gets 404 not found . Of course, since this happens asynchronously, you would not know this. Error messages will not be displayed.

The second problem is simpler. You said...

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

... when you meant ...

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

... or more correctly ...

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

It must be there.

+1
source

I have seen problems with redirecting web services where they will not work this way.

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

Or just do the HTML submission instead of calling the web service.

0
source

Since you are using ajax, this means that redirecting from the action will be ignored.

The solution to calling redirect might be to create another helper that uses the usual FORM POST and no ajax .. then the whole page will be POST and the action will be redirected.

Here is the part of my assistant that does just 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 at the above.

0
source

All Articles