MVC 5 多选列表值未绑定到发布时的模型
Posted
技术标签:
【中文标题】MVC 5 多选列表值未绑定到发布时的模型【英文标题】:MVC 5 Multiselect List Values Not Binding to Model On Post 【发布时间】:2016-09-23 14:09:58 【问题描述】:我有几个这样声明的多选列表的视图
<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);
在提交时,我可以查看浏览器发送的发布数据,它正在向服务器发送适当的数据
...&Counties=16&Counties=34&...
当动作开始执行时,模型中 Counties 的值为 null。但是我可以查看 FormCollection 的值,而 form["Counties"] 的值是 "16,34"。任何想法为什么绑定没有发生?
【问题讨论】:
【参考方案1】:我在发布问题后就注意到了这一点。问题是让 setter 受到保护。这会阻止活页夹设置列表的值。
【讨论】:
【参考方案2】:您还需要在发布事件时重置 ViewBag.CountyList 的值。
或者在模型中有一个属性并将该属性绑定到您的多选列表框。 类似的东西
包装器/模型
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
希望有效!!!
【讨论】:
以上是关于MVC 5 多选列表值未绑定到发布时的模型的主要内容,如果未能解决你的问题,请参考以下文章