Bind Checkboxes to int array/enumerable in MVC

耗尽温柔 提交于 2019-12-04 09:02:53

问题


@Html.CheckBox("orderNumbers", new { value = 1 })
@Html.CheckBox("orderNumbers", new { value = 2 })
@Html.CheckBox("orderNumbers", new { value = 3 })
@Html.CheckBox("orderNumbers", new { value = 4 })
@Html.CheckBox("orderNumbers", new { value = 5 })

[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<int> orderNumbers) { }

[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<string> orderNumbers) { }

If I use the first signature in my action method, I get an empty IEnumerable.

If I use the second signature I do receive the values but I also receive a false value for the unselected values (because of MVCs pattern of shadowing all checkboxes with a hidden field).

e.g. I will receive something like orderNumbers = { "1", "2", "false", "4", "false" }

Why can't I just get the list of numbers?


回答1:


Because thats how the provided CheckBoxFor helper is working.

You have to generate the html for the checkboxes yourself. Then the hidden inputs are not generated and you will get only the selected integer values.




回答2:


You can get all the checked values by the following way.

Controller code :

    public ActionResult Index()
    {            
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(string[] orderNumbers)
    {
        return View();
    }

View Code :

@using (Html.BeginForm())
{
    <input name="orderNumbers" type="checkbox" value="1" />
    <input name="orderNumbers" type="checkbox" value="2" />
    <input name="orderNumbers" type="checkbox" value="3" />
    <input name="orderNumbers" type="checkbox" value="4" />
    <input name="orderNumbers" type="checkbox" value="5" />

    <input type="submit" name="temp" value="hi" />
}

Please keep one thing in my mind that, you need to give same name to all checkboxes. In array you will get values for all checked checkboxes.




回答3:


In addition to alok_dida's great answer. Since all the values are integers, you can have your controller code take an array of integers and avoid doing the conversion yourself.

This works in MVC4+:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int[] orderNumbers)
{
    return View();
}


来源:https://stackoverflow.com/questions/8533972/bind-checkboxes-to-int-array-enumerable-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!