chamara
chamara

Reputation: 12711

Get Checkbox values to controller

In the below view i'm trying to get the checked checkbox values to the controller for saving in the database.

<div class="editor-label">
                <%: Html.LabelFor(model => model.Addresses) %>
            </div>

             <div class="editor-field">
             <% foreach (var item in Model.Addresses)
                { %>
       <input type="checkbox" 
         id="<%: item.addressID %>"
         name="addressOption"
         value="<%: item.addressID%>"/>
       <label for="optionId"><%: item.address%></label>
       <br />
         <% } %>
               </div>
               <br />
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Mobile) %>
            </div>

Controller:

AdvanceClient cli = new AdvanceClient();

                    if (ModelState.IsValid)
                    {

                        cli.Mobile = Request.Form["Mobile"];

                        foreach (var item in Request.Form["Addresses"])
                        {
                            //here i need to get the checked checkbox values
                        }
                    }

I'm stuck with getting the values of checked checkboxes

Upvotes: 0

Views: 3699

Answers (2)

the_lotus
the_lotus

Reputation: 12748

You can store arrays like this

<input type="checkbox" name="addressOption[0]" id="..." value="..." />
<input type="checkbox" name="addressOption[1]" id="..." value="..." />
<input type="checkbox" name="addressOption[2]" id="..." value="..." />

Now you just need to have an array in your model with the same name

List<int> addressOption;

and it will be populated automaticaly on submit.

Upvotes: 0

Sachin
Sachin

Reputation: 2148

You can get all values in comma separated string from :

var selectedValues = Request.Form["mySharedName"];
 // This is now a comma separated list of values that was checked

for you it will be : Request.Form["addressOption"]

after then using for loop you can get all values

Upvotes: 1

Related Questions