asp.net razor pages: why is my model not altered in my ActionResult

Viewed 32

I am showing some checkboxes in my page.

var lang = new LanguageManager().GetItems().ToList();
foreach (var item in lang)
{
    var res = new CheckedLangs
    {
        Name = item.Name,
        Id = item.Id,
        isChecked = false // todo
    };
    CheckedLanguages.Add(res);
}

<div class="divFormField">
    <table cellspacing="" cellpadding="0" border="0">
        <tr>
            <td class="Label">
                <label for="position">Sprachen</label>
            </td>
            <td class="Field">
                <table>
                    @for (int i = 0; i < Model.CheckedLanguages.Count; i++)
                    {
                        <tr>
                            <td class="js-export-checkbox">
                                @Html.HiddenFor(m => m.CheckedLanguages[i].Name)
                                @Html.CheckBoxFor(m => m.CheckedLanguages[i].isChecked)
                                <label>@Model.CheckedLanguages[i].Name</label>
                            </td>
                        </tr>
                    }
                </table>
            </td>
        </tr>
    </table>
</div>

They are displayed correctly. I see the text on them, and they all are set to false, so none of the boxes are checked.

If I check one, the first one for instance, and then check my model in the ActionResult I get this:

enter image description here

Its a list of all my checkboxes, with all the properties. But whats missing is that even though I checked one of the boxes, they all still have the value of "false" after I click save.

I must be missing one vital thing here. But I cant seem to find it? Can you help me out here?

1 Answers

Try to use

<input type="checkbox" name="model.CheckedLanguages[@i].isChecked" value="true"/>

to replace

@Html.CheckBoxFor(m => m.CheckedLanguages[i].isChecked)

Or you can try to set the default values of Model.CheckedLanguages[i].isChecked with true.

Related