2014-01-09 34 views
0

我有以下表格PurchaseQuery,Suppliers。但PurchaseQuery可以有多個供應商,因此添加了第三個表PurchaseQuerySupplier來保留兩個表的ID。 enter image description here在ASP.NET MVC中獲取服務器端的多選參數值

我有PurchaseQuery表單,其中我添加了一個多選列表來選擇多個供應商。

      @Html.ListBoxFor(model => model.PurchaseQuerySuppliers, new MultiSelectList(Suppliers.AsEnumerable(), "ID", "Name"), new { @class = "chosen-select"}) 

但在我的動作控制器中,我得到了PurchaseQuerySuppliers的空對象。雖然我可以在FormCollection中逗號分隔的供應商值,但我想在Purchase Controller中將PurchaseQuerySuppliers作爲PurchaseQuery中的對象。 有什麼建議嗎?

回答

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"/> 
} 
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" /> 
} 
相關問題