0

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...?

0

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

I added some more code to my answer. If you are having issues, let me know where and ill try to help.
I dont think only a part of your form body should be post as view model. Add a property to your view model and use editorFor<> or checkboxFor.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.