Change Id of MVC Radiobuttonfor or trigger jQuery function

1.6k Views Asked by At

Using the following notation in a MVC Radiobuttonfor helper I can create a radio which will have a default button selected if a value exists in the model.

@Html.RadioButtonFor(x => x.Username, "Y", Model.Username == "Y" ? new { Checked = "checked", id = "YUserName" } : null) No: 
@Html.RadioButtonFor(x => x.Username, "N", Model.Username == "N" ? new { Checked = "checked" } : null)

However the id = "YUserName" is not applied to the radio button with the value of "Y"

If I do not have the evaluation expression in the radiobuttonfor helper I can change the id of the radio with the value "Y" i.e.:

@Html.RadioButtonFor(x => x.UsePriorFinancialInfo, "Y", new { id = "YUsePriorFinancialInfo" }) 
@Html.RadioButtonFor(x => x.UsePriorFinancialInfo, "N")

Is there a way to apply a custom Id to one of the radio buttons with the evaluation expression? If not is there a way I can trigger a jQuery function if either radio button is selected? - Thanks

1

There are 1 best solutions below

5
On BEST ANSWER

Firstly, remove Checked = "checked". The RadioButtonFor helper will assign the value of checked. This works fine for me

@Html.RadioButtonFor(x => x.Username, "Y", Model.Username == "Y" ? new { id = "YUserName" } : null) Yes:
@Html.RadioButtonFor(x => x.Username, "N") No:

and rendered the following html

<input checked="checked" id="YUserName" name="Username" type="radio" value="Y">
<span>Yes</span>
<input id="Username" name="Username" type="radio" value="N">
<span>No</span>

Are you sure the value of property Username is set to "Y"?