user3398807
user3398807

Reputation: 1

Get values with Multiple checkboxes in Razor MVC4

Currently I'm working on MVC4 web application, I need to get values which are selected or not from multiple checkboxes from the web page. Here is my code in View to render checkboxes.

using (Html.BeginForm("Controller", "NameSpace", FormMethod.Post))
{          
     @foreach (var Leave in Model)
        {
            <tr class="Row">
                <td>
                    @Html.CheckBox("leaves")
                </td>
                <td>@Leave.EmployeeId</td>
                <td>@Leave.EmployeeName</td>
            </tr>
        }    
    <input type="submit" name="btn" value="Approve"/>
    <input type="submit" name="btn" value="Reject"/>
}

How can I get those checkBox's values in my controller...?

Upvotes: 0

Views: 7821

Answers (2)

Dudi
Dudi

Reputation: 3079

You better use:

string[] selectedList =Request.Form.GetValues("leaves");

Instead of:

string selected = Request.Form["leaves"].ToString();
string[] selectedList = selected.split(',');

for getting an array instead of one concatenated string which needed to be splitted.

Moreover, in this way you don't have to worry about having commas in your values.

Upvotes: 0

Matt Bodily
Matt Bodily

Reputation: 6413

put a name on the check box(es)and you can pull the value on the controller using request

@Html.CheckBox("leaves", new { name = "leaves" })

then on then controller

string selected = Request.Form["leaves"].ToString();
string[] selectedList = selected.split(',');
foreach(var temp in selectedList){
    // do something with the result
}

this will return a comma delimited list (1,5,8) of the id's of all of the selected checkboxes (if there are more than 1).

Upvotes: 1

Related Questions