【问题标题】:Read ViewData Sub Values读取 ViewData 子值
【发布时间】:2017-11-01 07:03:17
【问题描述】:

问:我怎样才能得到这个 ViewData? @ViewData["MyCustomCollection"]["MyParam1"] 它返回错误Cannot apply indexing with [] to an expression of type 'object'

查看(MyCustomCollecion 有[UIHint("MyCustomEditor")]

@Html.EditorFor(model => model.MyCustomCollection, new
{
    MyCustomCollection = new
    {
        Param1 = "MyParam1"
        Param2 = "MyParam2"
    }
})

我的自定义编辑器

(...)
<span>@ViewData["MyCustomCollection"]["MyParam1"]<span>
<span>@ViewData["MyCustomCollection"]["MyParam2"]<span>
(...)

重要提示:我需要将MyCustomCollection 设置为父级。我不能这样做:

@Html.EditorFor(model => model.MyCustomCollection, new
{
   Param1 = "MyParam1"
   Param2 = "MyParam2"
})

【问题讨论】:

  • 您绑定到名为MyCustomCollection 的属性,但随后还将名为MyCustomCollection 的对象传递为additionalViewData,这实际上没有意义。你的模型是什么,特别是 MyCustomCollection 属性
  • @StephenMuecke 我需要对具有不同 Param1 和 .因此,传递的属性名称是一种识别模板应该处理哪个编辑器的方法。我也会做MyCustomCollection_Param1AnotherCustomCollection_Param1 之类的事情,但我正在努力让事情变得更清洁。
  • 再说一次,这没有意义,尤其是您在编辑时声明 我不能这样做,因为您已经绑定到 MyCustomCollection
  • @StephenMuecke 好的,那么我该如何告诉我的EditorTemplate Param1 指的是 MyCustomCollection 或 AnotherCustomCollection?如果我在同一个视图中使用相同的 EditorTamplate 有 3 个属性,并让 Param1 执行 ViewData["Param1"] 会发生什么?
  • @Html.EditorFor(model =&gt; model.MyCustomCollection) 表示您绑定到名为MyCustomCollection 的属性。为什么您认为需要通过将另一个名为 MyCustomCollection 的不同对象作为附加视图数据发送到模板来覆盖所有这些。在不了解您的模型以及您实际编辑的内容的情况下,很难理解您在这里尝试做什么

标签: asp.net-mvc-4 viewdata


【解决方案1】:

按照这种方法,可以做我想做的事。

https://stackoverflow.com/a/47045595/3880331

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多