2011-07-20 37 views
0

this poster,我有点困惑ASP.NET MVC Html.ListBoxFor(...)。具体我把评选结果在一个名单,但之后我后的结果我得到困惑ASP.NET MVC Html.ListBoxFor(...)SelectExtension

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

这里是我传递到强类型的Razor视图

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的列表,而不是一组字符串,在后t时的视图代码o它认为我的模型无效的适当控制器动作:

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

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

+0

看看这个问题,它可能会帮助: http://stackoverflow.com/questions/2308846/why-is-listboxfor-not-selecting-items-but-listbox-is –

回答

1

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

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

+0

我试图将这些添加到控制器方法,启动视图 this.ModelState.Remove ( “SelectedDeclarations”); this.ModelState.Remove(“VendorsRequiringDeclaration”); 但是这些不是启动视图的控制器操作中ModelState的一部分,尽管它们位于传递给视图的模型中。 – mcmSEA

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 })