繁体   English   中英

ASP.NET MVC 5应用程序-如何在ajax发布后重定向到URL?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM