我想调用我的操作,让该操作返回直接呈现到视图上的结果部分视图,或者将操作重定向到服务器上的另一个页面。
但是,当我通过jQuery执行此操作时,它似乎将重定向的页面加载到我的目标div元素中,而不是干净利落地重定向并有效地重新加载页面/站点。
jQuery调用:
$.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操作示例
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");
}
}我是不是做错了?有没有更好的实践方法来做到这一点?这样做的需求将发生在其他操作和jQuery请求中,所以我正在寻找一种通用的方法来实现这一点。
更新:多亏了Andrews answer,我得到了我想要的东西,根据他的建议做了一些修改,改变了我的ajax。最终的ajax是:
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();
}
});
}});
发布于 2012-09-07 09:08:13
您不能从AJAX请求重定向。您将不得不从JavaScript执行重定向。我会推荐这样的东西:
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");
}
}然后在JavaScript端:
$.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);
}
}
});发布于 2012-09-07 09:08:08
您可以使用success回调的第二个或第三个参数来确定要做什么。无论如何,由于您使用的是ajax,您将无法执行正常的重定向。您可能需要通过javascript进行二次重定向,或者用从RedirectToAction返回的内容替换整个页面
https://stackoverflow.com/questions/12310437
复制相似问题