【问题标题】:MVC ListboxFor variable in modelMVC ListboxFor 模型中的变量
【发布时间】:2014-06-15 04:39:20
【问题描述】:

我有一个列表框

@Html.ListBoxFor(m => m.SelectedDepartment, Model.Departments, 
                 new { @class = "form-control", @style = "height:150px", size = 4,
                 onchange = "DepartmentSelectionChanged(this)" })

在我的模型中

 public IEnumerable<string> SelectedDepartment { get; set; }

但是在返回视图时我得到一个错误

System.InvalidOperationException:具有键的 ViewData 项 “SelectedDepartment”属于“System.String[]”类型,但必须属于“IEnumerable”类型。

怎么了?

我该如何纠正这个问题?

【问题讨论】:

  • 请在您设置 ViewData.SelectedDepartment 的地方添加控制器代码
  • 你能展示你的控制器吗

标签: c# asp.net-mvc html-helper html.listboxfor


【解决方案1】:

具有键“SelectedDepartment”的 ViewData 项的类型为“System.String[]”,但必须为“IEnumerableSelectListItem>”类型。

问题不在于IEnumerable / string[] 的使用,而在于您传递的是一组string 对象而不是SelectListItem 对象。

您可以轻松转换它:

List<SelectListItem> selectlistitems = new List<SelectListItem>();

foreach(string mystring in myarray)
{
    selectlistitems.Add(new SelectListItem() { Text = mystring, Value = mystring };
}

ViewData["SelectedDepartment"] = selectlistitems;

如果你使用 LINQ,它会更短:

ViewData["SelectedDepartment"] = 
        myarray.Select(mystring => new SelectListItem() { Text = mystring, Value = mystring })
            .ToList();

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    相关资源
    最近更新 更多