【问题标题】:How do I get the selected values of a checkbox list?如何获取复选框列表的选定值?
【发布时间】:2012-08-01 18:16:29
【问题描述】:

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

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

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

    ...
}

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

例如,如果复选框列表中的项目具有以下值:

猫。 1

猫。 2

猫。 3

猫。 4

...和Cat. 2Cat. 3 被选中,我怎样才能得到一个包含这些值的数组?

【问题讨论】:

    标签: asp.net-mvc checkboxlist


    【解决方案1】:

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

    [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
        ...
    }
    

    简单的问答,但希望它能帮助寻找答案的人(就像我刚开始学习 ASP.NET MVC 时一样)。

    附:如果您有更好或更详细的内容,请发布。

    【讨论】:

      【解决方案2】:

      查看这个问题的答案Here我一直都在使用它,而且效果很好。

      【讨论】:

        猜你喜欢
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多