Reputation: 3645
I want to make a call to my action and have that action either returned the resultant partial view that is rendered directly onto the view or have the action redirect to another page on the server.
However as I am doing this via jQuery it seems to load the redirected page into my target div element rather than redirecting cleanly and effectively reloading the page/site.
jQuery call:
$.ajax({
type: "GET",
url: "Myurl",
dataType: "html",
success: function (data) {
// replace the context of the section with the returned partial view
$('#upload_section').html(data);
}
});
MVC action example
public ActionResult MyAction()
{
bool doRedirect = // some code to determine this condition
if (doRedirect)
{
return RedirectToAction("MyAction", "Home");
}
else
{
// return the partial view to be shown
return PartialView("_UploadSessionRow");
}
}
Am I doing this all wrong? Is there a more best practice method for doing this? The need to do this will occur in other actions and jQuery requests so I''m looking for a common methodology for how to go about this.
Update: Thanks to Andrews answer I got what I was after by altering my ajax as per his suggestion with some modifications. Final ajax was:
function loadOrRedirect(options) {
var jData = null;
try {
if (options.data) {
jData = $.parseJSON(options.data);
if (jData.RedirectUrl) {
window.location = jData.RedirectUrl;
}
}
} catch (e) {
// not json
}
if (!jData && options.callback) {
options.callback(options.data);
}
};
$.ajax({
type: "GET",
url: "Myurl",
dataType: "html",
success: function (data) {
loadOrRedirect(
{
data: data,
callback: function (html) {
replaceRow.replaceWith(html);
alternateRowHighlighting();
}
});
}
});
Upvotes: 4
Views: 9988
Reputation: 126052
You can't redirect from an AJAX request. You are going to have to do the redirect from JavaScript. I would recommend something like this:
public ActionResult MyAction()
{
bool doRedirect = // some code to determine this condition
if (doRedirect)
{
return Json(new
{
RedirectUrl = Url.Action("MyAction", "Home")
});
}
else
{
// return the partial view to be shown
return PartialView("_UploadSessionRow");
}
}
Then on the JavaScript side:
$.ajax({
type: "GET",
url: "Myurl",
dataType: "html",
success: function (data) {
if (data.RedirectUrl) {
window.location = data.RedirectUrl;
} else {
// replace the context of the section with the returned partial view
$('#upload_section').html(data);
}
}
});
Upvotes: 19
Reputation: 5800
You could possibly use the second or third parameter of the success
callback to determine what to do. Regardless, since you are using ajax, you won't be able to do a normal redirect. You may have to do a secondary redirect via javascript or replace the whole page with what is returned from the RedirectToAction
Upvotes: 0