【问题标题】:MVC Redirect won't work if I call it outside the main function如果我在主函数之外调用它,MVC 重定向将不起作用
【发布时间】:2017-02-14 14:43:11
【问题描述】:

所以,当我点击一个按钮 - 它点击提交。我设法使 URL 值正常。我的问题是点击“RedirectingTime”功能不会重定向页面。它只是停止并显示一个空白页面。如果我将它放在 Submit 函数中,那么它可以正常工作,但我不想将我的提交从 void 更改为重定向,因为如果它出错,我还想返回一个视图。 谢谢!

    [HttpPost]
    public void Submit(URLModel model)
    {

        string url = EmailEnd(model);

        if (url != "0")
        {
            RedirectingTime(url);
        }
        else
        {
            Error();
        }
    }


    public RedirectResult RedirectingTime(string url)
    {
        return Redirect(url);
    }

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

根据下面的答案 - 工作代码是:

    [HttpPost]
    public ActionResult Submit(URLModel model)
    {

        string url = EmailEnd(model);

        if (url != "0")
        {
            return Redirect(url);
        }
        else
        {
            return View("Error");
}
        }
        }

【问题讨论】:

    标签: c# asp.net-mvc visual-studio controller


    【解决方案1】:

    问题是您的Submit 操作返回void。这将总是导致空白页,因为 void 本质上与EmptyResult 相同。

    点击的操作是返回结果的,而不是您从中调用的某个操作。即使RedirectingTime 返回重定向,您的Submit 操作也永远不会返回那个,因此结果仍然是EmptyResult 而不是RedirectResult

    此外,对于它的价值,显式设置操作返回值的类型是非典型且不必要的。几乎每个 MVC 操作签名都应该简单地将 ActionResult 作为返回。你可以实际上返回任何东西,RedirectResultViewResultJsonResult 等。

    【讨论】:

    • 完美。这就解释了为什么我什么都没得到。 +1
    【解决方案2】:

    您的问题的症结在于您的提交操作没有返回任何内容。它必须返回一个 ActionResult(或 ActionResult 的派生形式)。如果您想“重定向”到控制器上的另一个操作,请使用RedirectToAction。您可以使用或不使用参数,如下所示:

    [HttpPost]
    public ActionResult Submit(URLModel model)
    {
    
        string url = EmailEnd(model);
    
        if (url != "0")
        {
            return RedirectToAction("RedirectingTime", new { url = url });
        }
        else
        {
            return RedirectToAction("Error");
        }
    }
    
    public RedirectResult RedirectingTime(string url)
    {
        return Redirect(url);
    }
    
    public ActionResult Error()
    {
        return View();
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 2013-01-26
      相关资源
      最近更新 更多