![](/img/trans.png)
[英]How do I correctly Re-render a Recaptcha in ASP.NET MVC 2 after an AJAX POST
[英]ASP.NET MVC 5 application - How can I redirect to a URL after an ajax post?
我試圖在ajax發布成功后將用戶重定向到頁面。 會話變量確實發生了更改,但此后再也不會重定向。
控制器:
[HttpPost]
public ActionResult SelectFacility(string Facility)
{
System.Web.HttpContext.Current.Session["Facility"] = Facility;
return Json(new { redirectToUrl = Url.Action("Index", "Incident") });
}
Java腳本
$("#Facility").on("change", function () {
var fac = $(this).find("option:selected").text();
/*
$.post("/Incident/SelectFacility", {
Facility: fac
});
window.location = result.redirectUrl;*/
$.ajax({
url: '@Url.Action("SelectFacility","Incident")',
type: 'POST',
//contentType: 'application/json', not needed
//dataType: 'jsonp', jsonp is for sending to a site other than the current one
data: {
Facility: fac
},
success: function (result) {
if (result == true) {
window.location = result.redirectUrl;
}
}
});
});
首先, result
將容納一個對象,因此將其與true
進行比較是很奇怪的(盡管由於類型強制而實際上可以在這里工作)。
其次,邏輯的主要問題是,您正在檢查響應的redirectUrl
屬性,但正確的名稱是redirectToUrl
。
success: function(result) {
window.location = result.redirectToUrl;
}
但是,值得注意的是,在這種情況下,AJAX請求是完全多余的,因為您無論如何都要在頁面完成后立即重定向頁面。
我假設您在控制器中有操作,然后使用location.href
重定向您操作所在的位置。
$(document).on('click', '.functionName', function() {
swal({
title: "Are you sure?",
type: "info",
showCancelButton: true,
confirmButtonColor: "#2196F3",
confirmButtonText: "Yes, assign it!",
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function() {
$.ajax({
type: "post",
url: "User/Create",
ajaxasync: true,
success: function() {
swal("Assigned!", "User has been created!", "success");
location.href = "/User/Create";
},
error: function(data) {
swal("Oops", "Something went wrong!", "error");
}
});
您可以簡單地在ajax成功的MVC視圖中使用-
success:function() { window.localtion.href="@Url.Action("Index","Home")"; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.