I'm trying to deal with radiobutton ids in asp MVC 5
I'm working like this
Example model
class A
{
public bool? radio { get; set; }
}
and in razor view
@Html.RadioButtonFor(x => x.NeutroBT, Model.NeutroBT, new { @id = "True"})
@Html.RadioButtonFor(x => x.NeutroBT, !Model.NeutroBT, new { @id = "False})
It doesn't cause problem, but I'm working in an editortemplate, and I want it to have generated id
, to access in some way like @Html.IdFor(x => x.NeutroBT, true)
and @Html.IdFor(x => x.NeutroBT, false)
from the other views, just preventing changes in the future
Is some like this possible? I pass a lot of time searching and I didn't get anything similar
If is not possible, what is the best way to deal with it?
thanks!
There is no need to use an id
attribute. Instead you can just use the name
attribute to select or set the value via javascript (and in any case, @Html.IdFor() will only ever return
NeutroBT, not the
idthat you override in the
RadioButtonFor()` method so it cannot be used in your case)
In addition, the 2nd parameter of RadioButtonFor()
should be true
or false
(not Model.NeutroBT
and !Model.NeutroBT
).
And to associate a label with the button, you can wrap it in a <label>
, for example
<label>
@Html.RadioButtonFor(x => x.NeutroBT, true, new { id = ""})
<span>Yes</span>
</label>
<label>
@Html.RadioButtonFor(x => x.NeutroBT, false, new { id = ""})
<span>No</span>
</label>
Note that new { id = "" }
removes the id
attribute and prevents invalid html due to duplicate id
attributes.
Then to access the selected value using jQuery
var selectedValue = $('input[name="' + @Html.NameFor(x => x.NeutroBT) + '"]:checked').val();