如何获取复选框列表的选定值?

时间:2012-08-01 18:16:29

标签: asp.net-mvc checkboxlist

如果我在表单中有一个CheckBoxList,就像这样......

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

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

    ...
}

...如何在控制器操作中获取所选值列表(选中的值)?

例如,如果复选框列表包含值为:

的项目
  

猫。 1

     

猫。 2

     

猫。 3

     

猫。 4

...并选择Cat. 2Cat. 3,如何获取包含这些值的数组?

2 个答案:

答案 0 :(得分:1)

在最简单的情况下,控制器操作应该如下所示(在产品控制器中):

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

在更复杂的情况下(包含更多表单字段),最好使用视图模型,并为其添加Categories属性。

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&答,但希望它能帮助寻找答案的人(就像我第一次开始学习ASP.NET MVC时那样)。

P.S。如果你有更好或更详细的东西,请发布。

答案 1 :(得分:0)

查看这个问题的答案Here我一直都在使用它,它运作正常。

相关问题