【问题标题】:How to redirect to a view from controller while using XMLHttpRequest?使用 XMLHttpRequest 时如何从控制器重定向到视图?
【发布时间】:2016-11-13 12:01:37
【问题描述】:

我想在 ASP.NET MVC 中使用 XMLHttpRequest 显示一个字符串。 我无法使用以下代码从“PageSending”视图重定向到“PageReceiving”视图。 “PageReceiving2”只是一个将ToAction 重定向到“PageReceiving”视图的虚拟actionMethod,但在浏览器中,它不会重定向到“PageReceiving”视图,而是保留在“PageSending”视图上。

这是我的观点:

@{
ViewBag.Title = "PageSending";

}

页面发送

输入文字

@*<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>*@
<script>
  //  $(document).ready(
    function loadXML() {
       // alert("hello");
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/Test/PageReceiving2", false);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.onreadystatechange = function () {//Call a function when the state changes.
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                //  alert(xhttp.response);
                //location.href = "/Test/PageReceiving?Name=" + name;
            }
        }
        var name = document.getElementById("name").value;

        xhttp.send("Name=" + name);
    }
</script>

这里是控制器:

  using ProjectMVC1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace ProjectMVC1.Controllers
{



public class TestController : Controller
    {

        //
        // GET: /Test/

        //public ActionResult Index()
        //{
        //    return View();
        //}

        public ActionResult PageSending()
        {
            return View();
        }

        [HttpPost]
        public ActionResult PageReceiving2(Student stu)
        {

            return RedirectToAction("PageReceiving", new Student { Name = stu.Name });

            }
        public ActionResult PageReceiving(Student stu)
        {

            return View(stu);


        }


    }
}

【问题讨论】:

  • 你从服务器返回什么?假设您取消注释 location.href 行,它应该可以工作,但前提是 readystate 是 4 且 status 是 200。例如,如果您得到 500,那么这里不会发生任何事情。您可以使用浏览器的开发者控制台查看来自 AJAX 调用的原始响应。也就是说,在 AJAX 调用之后重定向是没有意义的。如果您仍然要重定向,不要使用 AJAX。只需发布一个标准表单,就可以收工了。
  • 取消注释“location.href”行,它正在工作,但我想从控制器actionMethods做重定向,这可能吗?或者是因为这是一个 AJAX 调用,所以这是不可能的(我知道在 AJAX 调用之后重定向是没有意义的,但我不知道这是一个 AJAX 调用......请原谅我)。 @ChrisPratt
  • 离开它。我发现它是 AJAX,这是一个愚蠢的问题,它可能会帮助将来遇到类似问题的人。

标签: c# asp.net asp.net-mvc-4 xmlhttprequest


【解决方案1】:

正如 Chris Pratt 所建议的,执行 Ajax 调用以重定向到其他操作是绝对没有意义的。从您的代码中,根本不清楚服务器返回的数据做了什么。

即便如此,如果你想重定向到其他动作,你可以调用这样的函数 -

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

参考 - Darin Dimitrov 的 post。

【讨论】:

    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多