AnonyMouse
AnonyMouse

Reputation: 18630

MVC components rendered as html components with the same id

say I have:

@Html.RadioButtonFor(modelItem => item.CheckerApproved, true)
@Html.LabelFor(modelItem => item.CheckerApproved, "Accepted")
@Html.RadioButtonFor(modelItem => item.CheckerApproved, false)
@Html.LabelFor(modelItem => item.CheckerApproved, "Rejected")

When I look at the page source I have something like:

<input id="item_CheckerApproved" name="item.CheckerApproved" type="radio" value="True" />
<label for="item_CheckerApproved">Approved</label>
<input checked="checked" id="item_CheckerApproved" name="item.CheckerApproved" title="" type="radio" value="False" />
<label for="item_CheckerApproved">Rejected</label>

The labels both associated to the first input.

It seems the inputs have the same id. Is this bad? How to get around it?

Upvotes: 1

Views: 213

Answers (2)

David Spence
David Spence

Reputation: 8079

You can get around this limitation by specifying an id for each of your radio buttons as shown below and then simply using Html.Label and specifying the id of your radio button for them to be linked.

<%= Html.RadioButtonFor(model => model.CheckerApproved, true, new { id = "Approved" })%>
<%: Html.Label("Approved")%>

<%= Html.RadioButtonFor(model => model.CheckerApproved, false, new { id = "Rejected" })%>
<%: Html.Label("Rejected")%>

Upvotes: 1

RPM1984
RPM1984

Reputation: 73112

The for attribute will get set to whatever you supply in the predicate for LabelFor.

Shouldn't this be a checkbox instead of two radiobuttons?

E.g:

@Html.CheckBoxFor(model => model.CheckerApproved)
@Html.LabelFor(model => model.CheckerApproved)

And yes - it's bad to have duplicate id's. It's not XHTML compliant, for one.

Especially if you start doing client-side scripting, your selectors will have issues:

$('#item_CheckerApproved'); // which checkbox will this retrieve? 

Upvotes: 1

Related Questions