Andrus
Andrus

Reputation: 27909

How to get list of checked boxes in controller

ASP.NET MVC 4 application allows to mark table rows. Razor view contains:

@using (Html.BeginForm())
{
<table class="table table-hover">
    @foreach (var f in Model.Failid)
    {
        <tr>
            <td>@f.FailiNimi</td>
            <td>
                @Html.CheckBox("c" + f.Id.ToString())
        </td>
    </tr>
    }
</table>

<input type="submit" class="btn btn-success" />
        @Html.AntiForgeryToken()

        }

If submit button is pressed, browser sends post request with body like

c40=false&c9=true&c9=false&c9=false&c10=false&c13=false

Controller signature is

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Failid(NameValueCollection nv)
{
...

However nv parameter value in controler is empty. Checkbox names are not passed as controller parameter.

How to get list of checked checkbox names in controller ?

Upvotes: 0

Views: 116

Answers (2)

Brian Mains
Brian Mains

Reputation: 50728

Your MVC controller should take FormCollection:

HttpPost, ValidateAntiForgeryToken]
public ActionResult Failid(FormCollection nv)

If nothing still comes back, verify the name is being rendered with your expectation. Also, I don't remember completely but do you have to set your own value with checkbox? In order to post something, a value must be specified, and this value is what gets sent back to the server, and then converted to a boolean by MVC.

Upvotes: 1

TigOldBitties
TigOldBitties

Reputation: 1337

Well, why would it show in a namevaluecollection? Try using Request.Form.AllKeys and Request.Form.GetValues(key)

Upvotes: 0

Related Questions