Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor - setting the id of a checkbox in a foreach loop

I'm looping through a list of vendors on my page, creating a checkbox for each one. I'd like to have each checkbox have an ID like "Vendor1", "Vendor30", where the number is the ID of the vendor.

I have this right now:

@foreach (var vendor in Model.Vendors) {
    <input id="@vendor.VendorID" type="checkbox" name="vendors" value="@vendor.VendorID" />
}

But that just gives me a number for the ID. I want to add "Vendor" to the front of it.

If I do this:

@foreach (var vendor in Model.Vendors) {
    <input id="[email protected]" type="checkbox" name="vendors" value="@vendor.VendorID" />
}

Every checkbox in the list has an id of "[email protected]".

I'm not using @Html.CheckBox because of the hidden field that comes along with it, and several other problems it was causing that I didn't include in this example.

like image 826
Steven Avatar asked Aug 23 '11 15:08

Steven


1 Answers

Try wrapping the razor expression in parantheses:

<input id="Vendor@(vendor.VendorID)" type="checkbox" name="vendors" value="@vendor.VendorID" />

I'm not using @Html.CheckBox because of the hidden field that comes along with it, and several other problems it was causing that I didn't include in this example.

Personally I've never had any problems with it and would recommend using it.

like image 155
Darin Dimitrov Avatar answered Nov 02 '22 23:11

Darin Dimitrov