混淆了ASP.NET MVC Html.ListBoxFor(...)SelectExtension

时间:2011-07-20 05:16:48

标签: asp.net-mvc

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的List而不是String的List,在发布到相应的控制器操作后,它认为我的模型无效:

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

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

2 个答案:

答案 0 :(得分:1)

如果ModelState无效,则需要重置控制器内的ViewData对象。

由于VendorsRequiringDeclaration内的数据未保存在任何地方。

答案 1 :(得分:1)

事实证明问题是我通过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 } )