ASP.NET MVC ListBoxFor Multiselect控件(值' 1,2'无效。)

时间:2016-12-01 22:07:15

标签: c# asp.net-mvc

我有一个带有多选列表的简单MVC应用程序,当前在提交时会抛出以下错误:值' 1,2'无效。

模型

public class FormData
{
    public int FormDataId { get; set; }

    [Required(ErrorMessage = "Please select at least one Type of Health Insurer")]
    [DisplayName("Type of Health Insurer")]
    public IEnumerable<SelectListItem> InsurerTypes { get; set; }
}

控制器

List<SelectListItem> typeItemList = new List<SelectListItem>();
        typeItemList.Add(new SelectListItem { Value = "1", Text = "Type A" });
        typeItemList.Add(new SelectListItem { Value = "2", Text = "Type B" });
        typeItemList.Add(new SelectListItem { Value = "3", Text = "Type C" });
        typeItemList.Add(new SelectListItem { Value = "4", Text = "Type D" });
        typeItemList.Add(new SelectListItem { Value = "5", Text = "Type E" });

        ViewBag.TypeItemList = typeItemList;

        if (ModelState.IsValid)
        {
            db.FormDatas.Add(formData);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(formData);

查看

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.InsurerTypes, htmlAttributes: new { @class = "required control-label col-md-2" })
        <div class="col-md-10">
            @Html.ListBoxFor(m => m.InsurerTypes, new MultiSelectList(ViewBag.TypeItemList, "Value", "Text"), new { @class = "form-control", Multiple = "multiple" })
            @Html.ValidationMessageFor(model => model.InsurerTypes, "", new { @class = "text-danger" })
        </div>
    </div>

我看过以下文章寻求帮助,但没有运气:

http://www.mikesdotnetting.com/article/265/asp-net-mvc-dropdownlists-multiple-selection-and-enum-support

http://www.mitechdev.com/2016/04/multi-select-dropdown-in-mvc5.html

修改 - 更新型号:

public class FormData
{
    public int FormDataId { get; set; }
    public IEnumerable<SelectListItem> InsurerTypes { get; set; }
    public IEnumerable<int> SelectedInsurers { get; set; }
}

模型现在似乎正常工作,因为我可以在db.FormDatas.Add(formData)上看到所选项目的列表。但是它似乎没有保存到数据库,因为该列只是null。

0 个答案:

没有答案