简体   繁体   中英

How to redirect user to another page from view after it was loaded is ASP .NET MVC?

For example I have some view with action link:

@Html.ActionLink("Action", "Controller")

Action action returns some view:

public ActionResult Action()
{
    string someModelForView = "some url i need to redirect after view was fully loaded";
    return View("SomeView", someModelForView);
}

What I need is to redirect user to url, defined in someModelForView model after view was fully loaded, and all javascripts on this page were executed. This view might be empty, without any content, I just need to execute some javascript, and after that redirect user to external page. How can accomplish that?

Once the view has been rendered and the JavaScript loaded, you (the server) have already sent your response (encapsulated in the returned ActionResult ) to the client (the browser). Thus, you cannot let ASP.NET MVC redirect you – the server has finished handling the request.

You can use JavaScript redirecting instead, though:

// Here goes your JavaScript code that needs to be executed
// ...

// ... and here comes the redirect:
window.location.href = "http://newurl.com";

You could do a redirect directly, as @achristov has suggested. But if you must return SomeView to execute the javascript you can use this:

@model string
<html>
    <head>
    </head>
    <body>
        <script type="text/javescript">
            $(document).ready( function() {
                // all your javascript code...
                // ...and then:
                window.location = "@Model";
            });
        </script>
    </body>
</html>

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