【发布时间】:2012-09-07 01:03:25
【问题描述】:
我想调用我的操作并让该操作返回直接呈现到视图上的结果部分视图,或者让操作重定向到服务器上的另一个页面。
但是,当我通过 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 请求中将需要执行此操作,因此我正在寻找一种通用方法来解决此问题。
更新: 感谢安德鲁斯的回答,我得到了我所追求的,按照他的建议修改了我的 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();
}
});
}
});
【问题讨论】:
-
RedirectToRoute("Default") and Redirect(returnUrl) are returning '200' instead of '302' 的可能重复项——关于那个问题的 OP 基本上是在做你自己的事情(AJAX 加载或重定向)
标签: jquery asp.net-mvc asp.net-mvc-3