简体   繁体   中英

How to redirect on the server side to override Angular.JS routing on a post?

I have created an ASP.NET MVC5 application which uses Angular.JS to control one of the pages. I am able to successfully post back to the ASP.NET controller using an $http.post , however, in the ASP.NET controller, if I try to return View("NewPage") or return RedirectToAction("NewPage", "Home") , it keeps me on my Angular.JS page.

Is there a way to override the client side Angular.JS routing, so that I can send the user to another view using the ASP.NET MVC controller?

Here's my Angular.JS post:

        $http.post("/calculator/post", vm.data)
            .then(function (response) {
                // Success

                // reset the data on a successful submit
                vm.data = {};
                vm.dataObjects = {};

            }, function (error) {
                // Failure
                vm.errorMessage = "Failed to find rates.";
            })
            .finally(function () {
                vm.isSubmitBusy = false;
            });

Here's my ASP.NET controller:

    //POST: Calculator
    [HttpPost]
    public ActionResult Post(CalcFormViewModel data)
    {
        if (ModelState.IsValid)
        {
           return View("NewPage");
        }

        TempData["Error"] = "An error occurred.";
        return RedirectToAction("Error");
    }

Using breakpoints in my ASP.NET controller, I can confirm that the return View() and return RedirectToAction() are being reached, however after a successful post, the page does not change in the browser.

That's because you're not asking the browser to navigate to a new resource. You're making a request with XMLHttpRequest . The response received by requests made with XMLHttpRequest can't affect the navigation of the browser. It would be down to you to interpret the response in the callback ( then clause), and to force a page change by fiddling with window.location.href in your javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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