Search code examples
asp.net-mvcrazorcheckboxfor

Multiple checkboxes in razor always return false


I had this problem: Multiple checkboxes in razor (using foreach)

I tried its solution. And it doesn't work for me. So hopefully you guys can help.

My View:

@for(int i = 0; i < Model.Messages.Count; i++)
{
    <tr>
        <td>
            @using (Html.BeginForm("UpdateMessage", "Home", FormMethod.Post))
            {
                @Html.CheckBoxFor(x => Model.Messages[i].Activated, new {onchange = "this.form.submit();"});
                @Html.HiddenFor(x => x.Messages[i].Text);
            }
        </td>
        <td>@Model.Messages[i].Text</td>
        <td><button>Delete</button></td>
    </tr>
}

Messages is a List of Message which has:

public string Text { get; set; }
public bool Activated { get; set; }

Controller POST method:

[HttpPost]
public ActionResult UpdateMessage(Domain.Entities.Message message)
{
    repository.UpdateMessage(message);

    return RedirectToAction("Settings_Message", "Home");
}

So I get a false bool and an empty string. Why?


Solution

  • You can use the following code for this. It will work.

    @using (Html.BeginForm("UpdateMessage", "Home", FormMethod.Post))
    {
         @Html.CheckBox("Activated", Model.Messages[i].Activated, new { onchange = "this.form.submit();" });
         @Html.Hidden("Text", Model.Messages[i].Text);                
    }