【问题标题】:How to redirect user to another page from view after it was loaded is ASP .NET MVC?加载后如何将用户重定向到另一个页面是 ASP .NET MVC?
【发布时间】:2012-11-09 16:46:37
【问题描述】:

例如,我有一些带有操作链接的视图:

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

Action 操作返回一些视图:

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

我需要的是在视图完全加载后将用户重定向到在someModelForView 模型中定义的url,并执行此页面上的所有javascript。这个视图可能是空的,没有任何内容,我只需要执行一些 javascript,然后将用户重定向到外部页面。如何做到这一点?

【问题讨论】:

  • 使用 jQuery 你可以 $(document).ready()
  • 如果没有内容,为什么必须在javascript中完成?为什么不直接使用 c#?

标签: c# javascript asp.net-mvc view controller


【解决方案1】:

一旦视图被渲染并加载了 JavaScript,您(服务器)已经将您的响应(封装在返回的 ActionResult 中)发送到客户端(浏览器)。因此,您不能让 ASP.NET MVC 重定向您——服务器已完成对请求的处理。

不过,您可以使用 JavaScript 重定向:

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

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

【讨论】:

    【解决方案2】:

    您可以按照@achristov 的建议直接进行重定向。但是如果你必须返回SomeView 来执行javascript,你可以使用这个:

    @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>
    

    【讨论】:

    • Model 将经常包含用户数据(例如,标题)
    • 但不是这个模型......所以你的咆哮不适用于这里。
    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多