Search code examples
c#asp.net-mvccheckboxchecked

set checkboxes to checked in view depending on condition


I have list of objects

        AAA.aListofObjects= (from tdrc in db.objectsDB
                                      where tdrc.objectID == id
                           select tdrc).ToList();

one parameter AAA.aListofObjects.check - holds true or false data.

Inside view I render my list using "for" where I have "If" statement to decide whether to check or not the checkbox

            @for (int i = 0; i < Model.aListofObjects.Count; i++)
    {
if(something equals something then I must render checkbox as checked)
{
 @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check)
}
else 
{
render unchecked checkbox
 @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check)
}

    }

Now how can I make them checked in this situation ? @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check, @checked="checked") does not help.

some aListofObjects[i].check are "true" and when I check html debugger I see that checkbox has value="true" status, but it is still unchecked. Why ?


Solution

  • In true condition to make checkbox checked you can set below code :

    @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check, new { @checked = "checked" })
    

    And for else condition to remain checkbox uncheck you can set below code :

    @Html.CheckBoxFor(modelItem => modelItem.aListofObjects[i].check)
    

    And you can get more details on @HTML.CheckboxFor here : Proper usage of .net MVC Html.CheckBoxForenter link description here