RadioButton helper and label
When using Mvc (beta) and rendering RadioButtons using the HtmlHelper they are rendered without any text or description. The label tag is used for this but is not rendered by the RadionButtons method.
Example;
<%=Html.RadioButton("MyRadioButton","MyValue")%>renders<input id="MyRadioButton" value="MyValue" name="MyRadioButton" type="radio">To get the label we just add the label tag and uses the input tags id as reference for the label.
<label for="MyRadioButton">My description</label>This will allow us to check the radio button by clicking on the label as well.
Then the problem occurs if we should use multiple radio buttons with the same name.
Example;
<%=Html.RadioButton("IsItRaining","Yes")%>
<%=Html.RadioButton("IsItRaining","No")%>This will renderrenders
<input id="IsItRaining" value="Yes" name="IsItRaining" type="radio">
<input id="IsItRaining" value="No" name="IsItRaining" type="radio">
This it not so well since we need different id attributes to be able to bind the label tags.
To fix this we need to add different ids to the input tags.
Example:
<%=Html.RadioButton("IsItRaining", "Yes", new {id="IsItRaining_Yes"})%><label for="IsItRaining_Yes">Yes</label>
<%=Html.RadioButton("IsItRaining", "No", new {id="IsItRaining_No"})%><label for="IsItRaining_No">No</label>That will produce the intended output;<input id="IsItRaining_Yes" type="radio" value="Yes" name="IsItRaining"/>And will work as below
<label for="IsItRaining_Yes">Yes</label>
<input id="IsItRaining_No" type="radio" value="No" name="IsItRaining"/>
<label for="IsItRaining_No">No</label>
1 comments:
Thanks for sharing this. Very helpful!
Post a Comment