Home > Software design >  Bind dynamic checkbox list to model is not working in razor pages
Bind dynamic checkbox list to model is not working in razor pages

Time:08-08

<div >
    <div >
        @for (var i = 0; i < Model.fruites.Count(); i  )
        {
            <div >
                <input type="checkbox" value="@Model.fruites[i].Id" name="Model.AssignedFruite" />
                <label>@Model.fruites[i].Name</label>
            </div>
        }
    </div>
</div>

Page Model

[BindProperty]
public List<string> AssignedFruite { get; set; }

CodePudding user response:

You are trying to bind a list with a CheckBox. You should either bind a list with a DropDownList or a bool with a CheckBox. Otherwise, if you must bind a list with a CheckBox list you can read this post

CodePudding user response:

To bind a List<String> to check boxes, ensure that the name attribute on every checkbox is identical and matches the name of the property you are binding to. Then assign the string for each item to the value attribute:

<div >
    <div >
        @for (var i = 0; i < Model.fruites.Count(); i  )
        {
            <div >
                <input type="checkbox" value="@Model.fruites[i].Name" name="AssignedFruite" />
                <label>@Model.fruites[i].Name</label>
            </div>
        }
    </div>
</div>

If you actually wanted to collect the Id of each item rather than its Name, bind to a List<int> instead (assuming that the Id is an int, not a GUID).

  • Related