[英]MVC RedirectToAction Doesn't Work After JSON Post Return
我正在嘗試在由MVC執行的AJAX流程的后期處理之后更改頁面。 我以不同的方式使用它,也許我的用法可能是錯誤的。
C#MVC代碼部分。 我正在發送int列表,它是用戶列表和進程並執行某些操作。
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
我的問題是MVC流程結束后,重定向部分不起作用。 流程有效,只有重定向無效。
JavaScript代碼在這里
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
將此添加到AJAX,它也無法正常工作
success: function() {
window.location.href = "@Url.Content("~/Courses/Index")";
}
使用AJAX后,瀏覽器將不會意識到響應。
當前格式的AJAX success
失敗,因為重定向響應代碼不是處於2xx
狀態而是3xx
您將需要檢查實際響應並根據重定向響應中發送的位置手動執行重定向。
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
需要任何人盡快工作的部分:
控制器部分:
return RedirectToAction("Index","Courses");
HTML部分:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "@Url.Content("~/Courses/Index")";
}
});
剛刪除
dataType:'json'
部分原因是我使用自己的數據類型而不是JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.