2012-08-01 60 views
0

如果我有一個表格內的CheckBoxList,像這樣...如何獲取複選框列表的選定值?

@using (Html.BeginForm("Save", "Product", FormMethod.Post)) 
{ 
    ... 

    @Html.CheckBoxList("Categories", Model.AllCategories); 

    ... 
} 

...我怎樣才能讓我的控制器動作來選擇值(選中值)的列表?

例如,如果該複選框列表與值項:

貓。 1

Cat。 2

Cat。 3

Cat。 4

...和Cat. 2Cat. 3被選中,我怎樣才能得到包含這些值的數組?

回答

1

在最簡單的情況下,控制器的動作應該是這樣的(在產品控制器):

[HttpPost] 
public ActionResult Save(string[] Categories) 
{ 
    // Process selected checkbox values here, using the Categories array 
    ... 
} 

在更復雜的情況下(有更多的表單字段),它可能是更好的使用視圖模型,併爲其添加「類別」屬性。

public class MyViewModel 
{ 
    ... 

    public string[] Categories { get; set; } 

    ... 
} 

控制器動作:

[HttpPost] 
public ActionResult Save(MyViewModel model) 
{ 
    // Process selected checkbox values here, using the model.Categories array 
    ... 
} 

簡單Q & A,但希望它會幫助別人尋找答案(像我,當我第一次開始學習ASP.NET MVC)。

P.S.如果您有更好或更詳細的內容,請發佈。

0

檢查出這個問題的答案Here我一直在使用它,它完美地工作。