【问题标题】:Using ViewBag from a different controller?使用来自不同控制器的 ViewBag?
【发布时间】:2012-03-21 23:45:12
【问题描述】:

我有一个操作方法 VerifyNewUser(),当用户单击其电子邮件中的 url(注册验证 url)时会调用该方法。

action 方法在 ViewBag 中设置一个 bool 属性,将用户更新为经过验证的用户,然后我加载主页,用户自动登录。在 /Home/Index 视图中,我想检查 ViewBag 中的属性我设置并显示一个 jquery ui 对话框,如果它是真的。

但是,我的 ViewBag 为空,脚本被跳过。注意我将消息存储在 homeController.ViewBag 中,所以我认为这会起作用。也许没有 ViewBag 有更好的方法来做到这一点?

public ActionResult VerifyNewUser()
    {
        if(everything checks out)  
        {
              HomeController homeController = new HomeController();
              homeController.ViewBag.RegisterationLoad = true;
              homeController.ViewBag.VerificationMessage = "Thank you! Your account has been activated";
              return View("../Home/Index", null);
        }
    }

Home 控制器没什么特别的:

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

在主页视图中,我有这段代码应该在单击验证 url 后检查主页是否正在加载,并且应该显示一个 jquery ui 对话框:

   @if (ViewBag.RegistrationLoad == "true")
   {
<script type="text/javascript">
    $("<div></div>").html("<span>@ViewBag.VerificationMessage</span>").dialog({
        width: 365, height: 165, minWidth: 365, minHeight: 165, maxWidth: 365, maxHeight: 165,
        autoOpen: true, modal: true, dialogClass: 'noTitleDialog', position: "center",
        buttons: {
            "Ok": function () {
                $(this).remove();
            }
        }
    });
</script>   
   }

感谢您的宝贵时间

【问题讨论】:

  • @ShankarSangoli 的答案似乎是您想要做的,但我注意到的一件事是,如果该行实际上正在执行,@if (ViewBag.RegistrationLoad == "true") 应该抛出异常,因为== 不会知道如何比较boolstring
  • 另一方面,如果您尝试访问一个 Action 中的 ViewBag 属性,该属性是在另一个 Action 中创建/设置的,那么您将需要另一个解决方案,我可以发布答案如果是这样的话。

标签: jquery asp.net view viewbag


【解决方案1】:

不要使用任何控制器来设置ViewBag 中的数据属性。只需正常设置它,它就可以在任何视图中访问。只要确保你正确使用它。在您的代码中,您在 ViewBag 中设置了一个布尔标志,并将它与一个总是会失败的字符串进行比较。

试试这个。

public ActionResult VerifyNewUser()
{
    if(everything checks out)  
    {
          ViewBag.RegisterationLoad = true;
          ViewBag.VerificationMessage = "Thank you! Your account has been activated";
          return View("../Home/Index", null);
    }
}

在视图中

   @if (ViewBag.RegistrationLoad == true)
   { 
        .....
        .....
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 2017-10-07
    • 2013-09-08
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多