Get Ids of Checked Checkboxes in MVC3
Asked Answered
C

1

5

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?

Catricecatrina answered 28/3, 2012 at 12:1 Comment(1)
Since the browser will post the input's name (actionChk), because they are all the same name you will get the array. Why not mangle the name to be actionChk17, actionChk18 etc?Gunsmith
D
10

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

Dung answered 28/3, 2012 at 12:11 Comment(1)
Simple and useful answer.Reata

© 2022 - 2024 — McMap. All rights reserved.