I’ve started using Razor and ASP.NET MVC3 and Code First for my latest projects and I’ve come across something that’s a bit disappointing. First, let me explain that I *hate* radio buttons that force you to actually hit that tiny, itty bitty, little, narrow spot with your mouse. I like to be able to click either the button or its related text. And, it’s easy to set up the HTML to do this. You simply use the “Label” tag for your text and the “For” attribute to identify the button. Really, truly simple.
OK, to the first annoyance. I’ve created a nifty script (in an earlier post) to create lists of radio buttons from SelectLists. Works like a charm, and creates the Label tags correctly. However, since I’ve started using Razor, I’ve discovered that my script does not include the tags for client-side verification (this is a topic for another day). So, what to do? First I go back to the old, built in “RadioButtonFor” helper and that’s OK, except that it generates radio buttons only. It won’t generate the “Label” tag that I like. And, it gets better. It creates the radio buttons in such a way that my trick with the “Label” tags won’t work. Isn’t that special?
The key to making my “Label” trick work is that the radio button controls need to have a unique ID attribute. Fortunately, we can force the old-style “RadioButtonFor” helper to provide a unique id, but we’re going to have to do it all by hand. Here’s the code to make it work:
@Html.RadioButtonFor(model => model.requirements, “Y”, new { id = “requirements_0″ })<label for=”requirements_0″>Yes</label> @Html.RadioButtonFor(model => model.requirements, “N”, new { id = “requirements_1″ })<label for=”requirements_1″>No</label>
You can see that we’re manually setting the ID’s in the RadioButtonFor helper, then referencing them in the Label and all is well. Except this is as ugly as homemade sin. So much for MVC and elegant HTML.
Oi.
Edit: And, finally a bit of good news. While my existing RadioButtonListFor class does not work with client-side validation, it still works well with the server side validations so all is not lost and my class remains (somewhat) useful for the time being.
This solution is worked for me.
Thanks Jagannath