我正在开发一个包含多选下拉列表的MVC应用程序。 我想获得下拉列表中多个选定项目的ID。
我有模型中的代码
namespace CustomerDEMOForMultiselect.Models
{
public class Customer
{
private int _ID;
private string _Name;
private double _Amt;
public int ID { get { return _ID; } set { _ID = value; } }
public string Name { get { return _Name; } set { _Name = value ; } }
public double Amt { get { return _Amt; } set { _Amt = value; } }
}
}
控制器代码
namespace CustomerDEMOForMultiselect.Controllers
{
public class CustomerController : Controller
{
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(CustomersList);
}
}
}
我没有在View中写到什么,我尝试了不同的代码但是我感到困惑......
视图中的代码:
@model CustomerDEMOForMultiselect.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>DisplayCustomer</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.DropDownListFor(v => v.ID, new MultiSelectList(ViewBag.CustList,"ID","Name",ViewBag.ID))
<br />
<input type="submit" value="Submit" />
}
</div>
</body>
</html>
我想在View中显示CustomerName list
,因此我可以选择多个客户名称并将选定的客户ID传回控制器。
怎么做?
答案 0 :(得分:15)
使用带有属性的包装器模型将所选客户绑定到工作(我试过):
包装模型:
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" />
}
您需要将选择绑定到控制器并将其发送回控制器。