jeudi 23 février 2017

How to set a checkbox to checked if a list contains an item with specific string?

I have code that gets a list of all colours a person is linked to through a DB table. If a person only has one favourite colour, the list will bring back 1 result. They can have as many as 3.

I have 3 existing checkboxes, that are by default not checked. They should be checked if the list item name brought back matches the colour. How do I change them to a checked state if the list item name matches the colour?

var ColoursLinkedToPerson = Model.Colours.ToList();

<p>Blue</p>
<input type="checkbox" name="Colour" id="checkBlue" value="Blue" /><br />

<p>Green</p>
<input type="checkbox" name="Colour" id="checkGreen" value="Green" /><br />

<p>Red</p>
<input type="checkbox" name="Colour" id="checkRed" value="Red" /><br />

foreach (var item in ColoursLinkedToPerson)
{
    if (item.Name == "Blue")
    {
         //Make the blue checkbox checked.  
    }
    // Same for Green
    // Same for Red
}

Open to simpler/other resolutions.




Aucun commentaire:

Enregistrer un commentaire