Search code examples
asp.net-mvcasp.net-mvc-3razorformcollection

Get Ids of Checked Checkboxes in MVC3


This is My View:

@foreach(var action in Model.Category.Actions) {
<div class="action" style="margin-right: 30px;">
    <input type="checkbox" class="chk-act" id="@action.Id" name="actionChk" />
    <text>@action.Text</text>
</div>
  }

And html Dom is like the followings:

<input type="checkbox" class="chk-act" id="17" name="actionChk">
<input type="checkbox" class="chk-act" id="18" name="actionChk">
<input type="checkbox" class="chk-act" id="19" name="actionChk">

So I need to get checked Ids. When I try to get values by form collection, that returned me an string array of on by length of checked checkboxes:

[HttpPost]
public ActionResult Index(FormCollection collection) {
    var actions = collection.GetValues("actionChk");
return View();
}

what is your suggestion?


Solution

  • You should put the values in the value parameter

     <input type="checkbox" class="chk-act" id="17" value="17" name="actionChk">
     <input type="checkbox" class="chk-act" id="18" value="18" name="actionChk">
     <input type="checkbox" class="chk-act" id="19" value="19" name="actionChk">
    

    Then, from the controller, you should have an array of Ids named actionChk