[英]ASP.NET MVC 5 application - How can I redirect to a URL after an ajax post?
I am trying to redirect the user to a page after the ajax post is successful. 我试图在ajax发布成功后将用户重定向到页面。 The session variable does get changed, but it never redirects afterwards. 会话变量确实发生了更改,但此后再也不会重定向。
Controller: 控制器:
[HttpPost]
public ActionResult SelectFacility(string Facility)
{
System.Web.HttpContext.Current.Session["Facility"] = Facility;
return Json(new { redirectToUrl = Url.Action("Index", "Incident") });
}
Javascript 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;
}
}
});
});
Firstly result
will hold an object, so comparing it to true
is rather odd (although will actually work here due to type coercion). 首先, result
将容纳一个对象,因此将其与true
进行比较是很奇怪的(尽管由于类型强制而实际上可以在这里工作)。
Secondly, and the main issue with your logic, is that you're checking the redirectUrl
property of the response, but the correct name is redirectToUrl
. 其次,逻辑的主要问题是,您正在检查响应的redirectUrl
属性,但正确的名称是redirectToUrl
。
success: function(result) {
window.location = result.redirectToUrl;
}
However, it's worth noting that in this situation the AJAX request is completely redundant as you're redirecting the page immediately after it completes anyway. 但是,值得注意的是,在这种情况下,AJAX请求是完全多余的,因为您无论如何都要在页面完成后立即重定向页面。
I assume in youn controller you have action, after that use location.href
to redirect where you action is located. 我假设您在控制器中有操作,然后使用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");
}
});
you can simply use in your MVC view in ajax success- 您可以简单地在ajax成功的MVC视图中使用-
success:function() { window.localtion.href="@Url.Action("Index","Home")"; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.