ASP.NET MVC3: How to redirect to a view when a post was made using AJAX? ASP.NET MVC3: How to redirect to a view when a post was made using AJAX? json json

ASP.NET MVC3: How to redirect to a view when a post was made using AJAX?


This question is a bit old, but I thought I would offer my input.I had a similar situation where I had to make a post and either populate some html on the page with update content, or redirect the user to a new location. There are probably better ways to accomplish this however, this is what I did.If you are using jQuery to perform the post it is smart enough to look at the response's content type; to return a view just do as you are now and in the success function populate the content. If you wish to redirect the user

        string javascript = "window.location.href='{0}';";        return JavaScript(string.Format(javascript, returnUrl));

The mvc framework will attach the javascript mime type to the response, jQuery will pick that up and execute the javascript, and redirect the user.The only catch is the javascript will be populated into the html content in your success method. To overcome this interrogate the content type for html, simmilar to here


I would suggest that you split it into two calls. In the first AJAX call check if it is a ViewResponse or a DialogResponse. If ViewResponse make another AJAX call to get the actual result object else make a non-AJAX server call to redirect to the new view.