我有以下表PurchaseQuery,供应商。但是,PurchaseQuery可以拥有多个供应商,因此添加了第三个表PurchaseQuerySupplier以保留两个表的ID。
我有PurchaseQuery表单,其中我添加了一个多选列表来选择多个供应商。
@Html.ListBoxFor(model => model.PurchaseQuerySuppliers, new MultiSelectList(Suppliers.AsEnumerable(), "ID", "Name"), new { @class = "chosen-select"})
但在我的Action Controller中,我获得了PurchaseQuerySuppliers的null对象。虽然我可以在FormCollection中逗号分隔Supplier值,但我想将PurchaseQuerySuppliers作为Action Controller中的PurchaseQuery内的对象。 有什么想法吗?
答案 0 :(得分:1)
您可以编写一个可以解决问题的视图模型。
public class PurchaseSupplierViewModel
{
public List<int> SelectedSupplies { get; set; }
public List<SelectListItem> Suppliers { get; set; }
}
和您的控制人员:
public ActionResult YourAction()
{
List<Supplier> SupplierList = (get all Suppliers from DB here)
var model = new PurchaseSupplierViewModel()
{
Suppliers = SupplierList.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name,
}).ToList()
};
return View(model);
}
[HttpPost]
public ActionResult YourAction(PurchaseSupplierViewModel model)
{
// model.SelectedSupplies will contain the selected Supplier IDs here
}
然后是观点:
@model PurchaseSupplierViewModel
@using (Html.BeginForm())
{
@Html.ListBoxFor(x => x.SelectedSupplies, Model.Suppliers, new { @class = "chosen-select" })
<input type="submit" value="Submit"/>
}
答案 1 :(得分:0)
以下是我将如何使用一些测试示例:
型号:
public class SuppliersModel
{
public List<Supplier> Suppliers { get; set; }
public string[] PurchaseQuerySuppliers { get; set; }
}
public class Supplier
{
public int ID { get; set; }
public string Name { get; set; }
}
操作:
public ActionResult ListTest()
{
var model = new SuppliersModel();
model.Suppliers = new List<Supplier>();
model.Suppliers.Add(new Supplier { ID = 1, Name = "Name1"});
model.Suppliers.Add(new Supplier { ID = 2, Name = "Name2" });
return View(model);
}
[HttpPost]
public ActionResult ListTest(SuppliersModel model)
{
string[] selectedItems = model.PurchaseQuerySuppliers;
return View(model);
}
查看:
@model SuppliersModel
@using (Html.BeginForm())
{
@Html.ListBoxFor(model => model.PurchaseQuerySuppliers, new MultiSelectList(Model.Suppliers.AsEnumerable(), "ID", "Name"), new { @class = "chosen-select"})
<input type="submit" value="submit" />
}