【问题标题】:How to return ActionResult with specific View (not the controller name)如何使用特定视图(不是控制器名称)返回 ActionResult
【发布时间】:2014-12-09 03:38:07
【问题描述】:

我在 MVC 控制器中有一个方法 SendMail。该方法调用其他方法 ValidateLogin。这是验证登录的签名:

private ActionResult ValidateLogin(Models.ResetPassword model)

当我从 SendMail 调用 ValidateLogin 时,出现此异常是因为控制器尝试搜索视图 SendMail,但我想加载 ResetPassword 视图:

Global Error - The view 'SendMail' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...

这是发送邮件的代码:

public ActionResult SendMail(string login)
{
        return ValidateLogin(login);
}

如何在 return 语句上覆盖视图?

提前致谢

【问题讨论】:

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


    【解决方案1】:
    private ActionResult SendMail(string login)
    {
                return View("~/Views/SpecificView.cshtml")
    }
    

    您可以通过明确指向它们的位置来直接指向特定视图..

    【讨论】:

      【解决方案2】:

      最后,这就是解决方案

      return View("ResetPassword", new ResetPassword
                  {
                      fields= fields
                  });
      

      【讨论】:

      • 只是一个小补充:这将要求“ResetPassword.cshtml”应该位于目录“~/Views//”中。其中 仅等于访问的控制器类的名称;例如: TestController >> "~/Views/Test/ResetPassword,cshtml" 将被访问以进行加载。不要在这里挣扎,否则您将无法加载任何内容。 ;)
      【解决方案3】:

      View 方法有一个重载,可以将字符串传递给viewName。有时您想将string 作为模型传递,而asp.net 框架会混淆它试图查找具有值string 的视图。试试这样的:

      public ActionResult SendMail(string login)
      {
         this.Model = login; // set the model
         return View("ValidateLogin"); // reponse the ValidateLogin view
      }
      

      【讨论】:

        【解决方案4】:

        如果 SendMail 是 POST,您应该使用 POST-REDIRECT-GET 模式

            public ActionResult SendMail(string login)
            {
                ...        
                return RedirectToAction("ResetPassword", login);
            }
        
            public ActionResult ResetPassword(string login)
            {
                ...
                return View("ResetPassword", login);
            }
        

        这将保护您免受 IE 中的双重发布

        【讨论】:

          【解决方案5】:

          您可以通过这样的名称返回视图

          return View("viewnamehere");
          

          【讨论】:

          • 仅当视图来自同一个控制器时,否则将无法加载。
          猜你喜欢
          • 1970-01-01
          • 2020-09-27
          • 1970-01-01
          • 2010-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-04
          • 1970-01-01
          相关资源
          最近更新 更多