【问题标题】:confused by ASP.NET MVC Html.ListBoxFor(...) SelectExtension被 ASP.NET MVC Html.ListBoxFor(...) SelectExtension 困惑
【发布时间】:2011-07-20 05:16:47
【问题描述】:

就像this poster,我对 ASP.NET MVC Html.ListBoxFor(...) 有点困惑。具体来说,我将选择结果放在列表中,但在发布结果后,我得到了

InvalidOperationException: The ViewData item that has the key 'SelectedDeclarations' is of type 'System.String[]' but must be of type 'IEnumerable<SelectListItem>'

这是我传递给强类型剃刀视图的缩写 ViewModel

public MyViewModel 
{
    public MyViewModel()
    {
        (...)
        this.VendorsRequiringDeclaration = new List<SelectListItem>();
        this.SelectedDeclarations = new List<String>();
    }

    public IEnumerable<String> SelectedDeclarations { get; set; }
    public List<SelectListItem> VendorsRequiringDeclaration { get; set; }
}

这里是引用它们的视图代码

      @Html.ListBoxFor(m=>m.SelectedDeclarations, Model.VendorsRequiringDeclaration, new { @class="editor-field", @size=6})

如果我将 MyViewModel 更改为 SelectedDeclarations 是 SelectedListItem 列表而不是 String 列表,则在发布到适当的控制器操作后,它会认为我的模型无效:

{"The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types."}

想法?我可能对第一个参数有错误的 LINQ 表达式,但我无法从类似的问题中看到它。提前致谢!

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

ModelState无效的情况下,需要重置控制器内部的ViewData对象。

因为VendorsRequiringDeclaration 中的数据没有保存在任何地方。

【讨论】:

  • 我尝试将这些添加到启动视图的控制器方法中 this.ModelState.Remove("SelectedDeclarations"); this.ModelState.Remove("VendorsRequiringDeclaration");但这些不是启动视图的控制器操作中的 ModelState 的一部分,尽管它们在传递给视图的模型中。
【解决方案2】:

事实证明,问题在于我通过 EF 访问的基础数据表的 SQL 权限;该帖子失败并使其看起来像是 Html Helper —— 如有任何混淆,我们深表歉意!

根据 AlexanderB 的建议,尽管我确实重新设计了 Html.ListBoxFor(...),但它似乎工作正常:

             @Html.ListBoxFor(m=>m.SelectedDeclarations,
                              new MultiSelectList(
                              Model.VendorsRequiringDeclaration,
                              "Id",
                              "VendorName",
                              Model.VendorsRequiringDeclaration.Select(
                                 x => new SelectListItem()
                                          {
                                              Selected = false,
                                              Text = x.VendorName,
                                              Value = x.Id.ToString()
                                          }).ToList()),
                          new { @class = "editor-field", @size = 6 } )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-06
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多