Bind Checkboxes to int array/enumerable in MVC

fearofawhackplanet picture fearofawhackplanet · Dec 16, 2011 · Viewed 17.4k times · Source
@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?

Answer

alok_dida picture alok_dida · Dec 16, 2011

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.