【问题标题】:MVC MultiSelectList BindingMVC 多选列表绑定
【发布时间】:2014-10-20 23:58:36
【问题描述】:

我使用 ASP.NET MVC .. 当我发布我的表单时,它会在我的模型验证时引发转换错误。如何修复我的视图模型或其他验证方式?

“从类型 'System.String' 到类型 'System.Web.Mvc.SelectListItem' 的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。” 谢谢。。

//my view model
public class ProdGroupViewModel
{
    //I've to fixed here or another way?
    public IEnumerable<SelectListItem> Rooms { get; set; }
}


//controller
public ActionResult Create(int id)
{
    return View(new ProdGroupViewModel
            {
                Rooms = new MultiSelectList(_roomService.GetAll(), "RoomId", "RoomName"),
            });

}

//in my view
<div class="form-group">
    <label class="col-md-3 control-label">Oda</label>
    <div class="col-md-9">
        @Html.ListBoxFor(model => model.Rooms, (MultiSelectList)Model.Rooms, new { @class = "form-control" })
    </div>
</div>

【问题讨论】:

    标签: asp.net-mvc validation razor


    【解决方案1】:

    您正在尝试发布到包含您的选择列表的同一属性。列表框中选择的发布结果将是一个逗号分隔的选定选项值字符串,modelbinder 无法将其绑定到 MultiSelectList 类型的属性。

    您需要一个额外的模型属性来保存发布的值,例如:

    public List<int> SelectedRoomIds { get; set; }
    

    然后在你看来:

    @Html.ListBoxFor(m => m.SelectedRoomIds, Model.Rooms, new { @class = "form-control" })
    

    另外,您不需要转换 Model.Rooms,因为它已经是强类型的。

    【讨论】:

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