dre*_*eza 3 asp.net-mvc jquery asp.net-mvc-3
我想调用我的操作并让该操作返回直接呈现在视图上的结果局部视图,或者让操作重定向到服务器上的另一个页面.
然而,由于我通过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);
}
});
Run Code Online (Sandbox Code Playgroud)
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");
}
}
Run Code Online (Sandbox Code Playgroud)
我做错了吗?这样做有更好的练习方法吗?在其他操作和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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
});
And*_*ker 18
您无法从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");
}
}
Run Code Online (Sandbox Code Playgroud)
然后在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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8743 次 |
| 最近记录: |