How to display one element based on whether there is such a value in the model?

Viewed 60

I have a code like this:

<label>Manufacturer:</label>
<input type="checkbox" name="brand" value="A" /><span>A</span>
<input type="checkbox" name="brand" value="B" /><span>B</span>
<input type="checkbox" name="brand" value="C" /><span>C</span>
<input type="checkbox" name="brand" value="D" /><span>D</span>

Input can be infinite.

How to check if the model has "brand" with a certain value? If there is, then output "input", if not, do not output.

I tried to do this, but it's dumb.

@model IEnumerable<BeautySouthKoreaSiteMVC.Models.Cosmetic>

@{
    int i = 0;
    foreach (var b in Model)
    {
        if (b.Brand.Contains("A") && i == 0)
        {
            <input type="checkbox" name="brand" value="A" /><span>A</span>
            i++;
        }
    }
}

The there is the model definition:

public class Cosmetic
{   
   [Display(Name = "Brand")]
   public string Brand { get; set; }

   // Some properties here...

}
1 Answers

So, idea is using FirstOrDefault() with predicate on the collection:

@if (Model.FirstOrDefault(p => p.Brand == "A") != null) 
{
    <input type="checkbox" name="brand" value="A" /><span>A</span> 
}
   
Related