17

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 + '&storeKey=@Model.StoreID',
            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

Y2theZ
  • 10,162
  • 38
  • 131
  • 200

3 Answers3

25

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
   }
});
Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Thank you it worked. If you have some time can you tell me how can I use an action with parameters? how to pass her parameters? – Y2theZ Apr 16 '12 at 17:25
  • @Youssef: I dont think you can pass parameters to this from javascript as you do with razor. You need to build a hardcoded url for that. – Shyju Apr 16 '12 at 17:30
8

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 { ... });
}
faisale
  • 1,435
  • 14
  • 14
2

Try

window.location = "/Store/Stores";

Instead.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147