Search code examples
htmlasp.net-mvc-5

Found 2 elements with non-unique id for Radio Buttons MVC


I have this Gender field on an MVC page that generates an error in Chrome's console for duplicate IDs

    <div class="form-group row">
        @Html.LabelFor(m => m.UserGender, new { @class = "col-sm-4" })
        <div class="col-sm-6">
            <label>@Html.RadioButtonFor(m => m.UserGender, "true") Male </label>
            <label>@Html.RadioButtonFor(m => m.UserGender, "false") Female </label>
        </div>
    </div>

Here is Chrome's console output:

Registration:1 [DOM] Found 2 elements with non-unique id #UserGender: (More info: ...) <input data-val=​"true" data-val-required=​"The Gender field is required." id=​"UserGender" name=​"UserGender" type=​"radio" value=​"true">​ <input id=​"UserGender" name=​"UserGender" type=​"radio" value=​"false">​

I have a couple of such errors on the page. How do I set up radio button options to prevent this?

Research

I found out a way to add a random id to each radio element to fix the console vomiting the warnings but am not sure if there is a proper way to handle this in MVC:

<label>@Html.RadioButtonFor(m => m.UserGender, "true", new { id = "radio" + Guid.NewGuid(), @checked = "checked" }) Male </label>

Solution

  • Apparently, adding the is through HTML attribute is the only way:

    <label>@Html.RadioButtonFor(m => m.UserGender, "true", new { id = "radio" + Guid.NewGuid(), @checked = "checked" }) Male </label>