umbraco - 如何将 ViewData 和 ViewBag 与 Umbraco 表面 Controller 一起使用

标签 umbraco viewbag viewdata surface-controller

我刚刚花了 2 个小时试图弄清楚为什么当我将一个字符串放入我的 Surface Controller 中的 View.Bag/ViewData 时,当我尝试在 View 中取回该字符串时我得到 null。

最后,我通过将字符串放入 session 变量中解决了这个问题。

想知道为什么它不起作用,以及如何修复它。

提前致谢。

最佳答案

更新:您在发帖和重定向吗?当您刷新表单时,它会提示您重新发布吗?如果不是,那是因为您不小心遵循了表单发布的 302ing 最佳实践(防止用户刷新和重新发布表单数据)。我遵循的登录表面 Controller 的示例都使用了 return RedirectToCurrentUmbracoPage() 我盲目地遵循了。但是,顾名思义,真的是在做重定向,而且真的是两个请求! (我固执的要在Fiddler里验证才相信)。 ViewData 和 ViewBag 仅适用于一个请求——因此它们在 POST 302 中根本被破坏。 session 适用于多个请求,这就是它对您有用的原因。 TempData 也适用于您,因为事实证明,TempData 是一种构建在 session 之上的构造,专门设计用于在两个帖子之间传输状态(在检索时删除)。我在某处读到,将 TempData 命名为 RedirectData 会更好,这有助于我点击它。

因此,当您处理 Surface Controller 和 POST 时,您有三个我知道可行的选项:

  • session (你证明有效)
  • TempData(它建立在 session 之上,从我读到的内容来看,这既是最佳实践,也是专门为这种情况而构建的)
  • 在表单发布中使用 return CurrentUmbracoPage();。我刚刚在Fiddler中验证了这正是一个请求(在浏览器中刷新提示重新发布警告)。我还验证了 ViewData 以这种方式工作。但是,因为表面 Controller 是使用 @Html.Action(...) 呈现为子操作,所以您必须使用 ParentActionViewContext 来获取正确的 ViewData(我的第一个我会留给发现这个问题的其他人的答案)。

当不涉及重定向(GET 或返回 CurrentUmbracoPage())的 POST 时,原始答案仍然有用...

在许多情况下,您实际上是在执行子操作。通常你只有一层深度,但如果你混合使用宏和部分,你实际上可以获得多层深度。每个级别都有一个 ViewData,您必须使用 ParentActionViewContext 在堆栈中向上走,才能到达您在 Controller 中填充的顶部 ViewData

参见 this comment from Shannon在回答有关表面 Controller 和 View 数据的问题时(Shannon 是 HQ 团队的核心贡献者,并且有很多很棒的内容)。此处引用:

If you want to access the ViewData that you've set on the master ViewContext's on a ChildAction being rendered from the master's ViewContext then you need to use @ViewContext.ParentActionViewContext.ViewData["ErrorMessage"]

The ParentActionViewContext in this example is the ViewContext that is rendering the Umbraco template, not the ChildAction. That is because when you POST (whether inside of Umbraco or normal MVC), you are posting to a new Action and the rendering process starts from scratch, when you validate your model, update the ViewData, etc... this all happens on what will become the 'master' ViewContext when the view renders. This view then will render your ChildAction.

关于umbraco - 如何将 ViewData 和 ViewBag 与 Umbraco 表面 Controller 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990225/

相关文章:

asp.net-mvc - 在 Umbraco 中创建基于插件的 Controller

asp.net-mvc - 如何在 Razor 中检查查看袋的内容

c# - 无法对空引用执行运行时绑定(bind)。 ViewBag.Title 为空

ruby-on-rails - 在 View 中访问数据库对象(和其他重要数据)

c# - 为什么 Html.DropDownListFor 需要额外的转换?

jquery - 如何使用jquery mvc从json读取数据到View

c# - Umbraco 7 + Razor : How to get a Document/Node by ID?

c# - 为什么 Umbraco WYSIWYG 在标签链接前放置正斜杠?

c# - 获取数组中的最后一个 child

javascript - 如果参数不在 AJAX 调用期间,则包含 NULL 条目