-1

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 ?

David
  • 4,332
  • 13
  • 54
  • 93
  • Can't you just bind the value of `something equals something then I must render checkbox as checked` to the checkbox? https://stackoverflow.com/a/43551907/169714 – JP Hellemons Oct 25 '18 at 08:40
  • If the value of the property is `true`, then the checkbox will be checked. If its `false` it will not be. That is how model binding works. You do not need and `if/else` block, and you do not set the `checked` attribute (the `CheckBoxFor()` method sets it correctly based on the value of the property) –  Oct 25 '18 at 08:42
  • Related issues: https://stackoverflow.com/questions/46804274/check-the-checkbox-based-on-model-in-mvc & https://stackoverflow.com/questions/6157293/how-do-i-set-a-checkbox-in-razor-view. The assignment for `CheckBoxFor` is redundant and you should set checked state on viewmodel property. – Tetsuya Yamamoto Oct 25 '18 at 08:44
  • Exactly what I said. You could also use the general `Html.EditorFor`. Because the property is a bool it will render a checkbox. – JP Hellemons Oct 25 '18 at 08:45
  • 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 ? – David Oct 25 '18 at 08:54

1 Answers1

0

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

Mohan Rajput
  • 634
  • 9
  • 21