Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 redirect to action after ajax call

In an ASP.NET MVC3 Application I have a button in the view.

When the button is clicked a function is called and it jquery ajax call is made to save items to the database

    function SaveMenuItems() {
        var encodeditems = $.toJSON(ids);;
        $.ajax({
            type: 'POST',
            url: '@Url.Action("SaveItems", "Store")',
            data: 'items=' + encodeditems + '&[email protected]',
            complete: function () {
                    }
                }
            });
        }

What i want is after the items are saved to the database I want to redirect to another view. (Redirect to action)

How can I do that?

I tried to use return RedirectToAction("Stores","Store") in the controller at the end of the SaveItems function. But it is not working

I also tried to add window.location.replace("/Store/Stores"); in the complete function of the ajax call but didn't work either

Any help is greatly appreciated

Thanks a lot

like image 403
Y2theZ Avatar asked Apr 16 '12 16:04

Y2theZ


2 Answers

You can use javascript to redirect to the new page. Set the value of window.location.href to the new url in your ajax call's success/complete event.

var saveUrl = '@Url.Action("SaveItems","Store")';
var newUrl= '@Url.Action("Stores","Store")';

$.ajax({
    type: 'POST',
    url: saveUrl,
    // Some params omitted 
    success: function(res) {
        window.location.href = newUrl;
    },
    error: function() {
        alert('The worst error happened!');
    }
});

Or in the done event

$.ajax({      
    url: someVariableWhichStoresTheValidUrl
}).done(function (r) {
     window.location.href = '@Url.Action("Stores","Store")';
});

The above code is using the Url.Action helper method to build the correct relative url to the action method. If your javascript code is inside an external javascript file, you should build the url to the app root and pass that to your script/code inside external js files and use that to build the url to the action methods as explained in this post.

Passing parameters ?

If you want to pass some querystring parameters to the new url, you can use this overload of the Url.Action method which accepts routevalues as well to build the url with the querystring.

var newUrl = '@Url.Action("Stores","Store", new { productId=2, categoryId=5 })';

where 2 and 5 can be replaced with some other real values.

Since this is an html helper method, It will work in your razor view only,not in external js files. If your code is inside external js file, you need to manually build the url querystring parameters.

Generating the new url at server side

It is always a good idea to make use of the mvc helper methods to generate the correct urls to the action method. From your action method, you can return a json strucutre which has a property for the new url to be redirected.

You can use the UrlHelper class inside a controller to do this.

[HttpPost]
public ActionResult Step8(CreateUser model)
{
  //to do : Save
   var urlBuilder = new UrlHelper(Request.RequestContext);
   var url = urlBuilder.Action("Stores", "Store");
   return Json(new { status = "success", redirectUrl = url });            
}

Now in your ajax call's success/done callback, simply check the return value and redirect as needed.

.done(function(result){
   if(result.status==="success")
   {
      window.location.href=result.redirectUrl;
   }
   else
   {
      // show the error message to user
   }
});
like image 189
Shyju Avatar answered Oct 31 '22 03:10

Shyju


In action you can write this:

if(Request.IsAjaxRequest()) {
    return JavaScript("document.location.replace('"+Url.Action("Action", new { ... })+"');");  // (url should be encoded...)
} else {
    return RedirectToAction("Action", new { ... });
}
like image 8
faisale Avatar answered Oct 31 '22 02:10

faisale