MVC 5 多选列表值未绑定到 Post 上的模型

MVC 5 Multiselect List Values Not Binding to Model On Post

我有一个包含多个多选列表的视图,这些列表是这样声明的

<div class="col-md-6">
    @Html.LabelFor(model => model.Counties, htmlAttributes: new { @class = "control-label" })
    @Html.ListBoxFor(model => model.Counties, new MultiSelectList(ViewBag.CountyList, "Value", "Text"), htmlAttributes: new { @class = "form-control", size = 8, tabindex = 26 })
    @Html.ValidationMessageFor(model => model.Counties, "", new { @class = "text-danger" })
    <span class="small">Ctrl + click to select multiple items</span>
</div>

我的视图模型包含这样的声明:

 public virtual List<long> Counties { get; protected set; }

我的动作是这样的:

    [HttpPost]
    public ActionResult Edit(TScholarshipView model, FormCollection form)
    {
        if (ModelState.IsValid)
        {
            TScholarship scholarship = Repo.GetScholarship(model.Id);
            scholarship = Mapper.Map<TScholarshipView, TScholarship>(model, scholarship);
            Repo.SaveOrUpdate(scholarship, HttpContext.User.Identity.Name);

            return RedirectToAction("Edit", "AdminScholarship", new { id = model.Id });
        }

        return View("Scholarship", model);
    }

提交时我可以查看浏览器发送的 post 数据,它正在向服务器发送适当的数据

...&Counties=16&Counties=34&...

当动作开始执行时,模型中Counties的值为空。但是我可以查看 FormCollection 值,并且 form["Counties"] 的值是“16,34”。任何想法为什么没有发生绑定?

您还需要在 post 事件中重置 ViewBag.CountyList 的值。

或者在模型中有一个 属性 并将那个 属性 绑定到您的多 select 列表框。 像

包装器/模型

public class CustomerList
{
    public List<Customer> Customers { get; set; }
    public List<int> SelectedIDs { get; set; }
}

控制器

[HttpGet]
public ActionResult DisplayCustomer()
{
    Customer oCustomer = new Customer();
    List<Customer> CustomersList = new List<Customer>();
    CustomersList.Add(new Customer() { ID = 1, Name = "TestCustomer1", Amt = 123 });
    CustomersList.Add(new Customer() { ID = 2, Name = "TestCustomer2", Amt = 234 });
    CustomersList.Add(new Customer() { ID = 3, Name = "TestCustomer3", Amt = 324 });
    ViewBag.CustList = CustomersList;
    return View(new CustomerList() { Customers = CustomersList }); 

}

[HttpPost]
public void DisplayCustomer(List<int> selectedIds)
{
    // do something with the id list
}

查看

@model MvcApplication2.Models.CustomerList

@using (Html.BeginForm(@Model.SelectedIDs))
{
    @Html.ListBoxFor(m => m.SelectedIDs, new MultiSelectList(@Model.Customers, "ID", "Name", @Model.SelectedIDs))
    <input type="submit" value="save" />
}

如前所述here

希望有用!!!

我在发布问题后立即注意到了这一点。问题是 setter 受到保护。这阻止了活页夹设置列表的值。