Razor RadioButton ViewModel Property Binding
-
Hi, I'm having a hard time finding a simple enough (ELI5) direct answer to on here and the interwebz If I have the following html fragment on a razor page. How does the clicked button bind to the viewmodel Gender property (transfer data to/from viewmodel property and radiobutton input element)? If I understand it correctly, this binding happens server-side after a POST. This fragment below would have been inside a form, so ALL (male, female in this case) the radio button input types will get sent together with the hidden element. The expression parameters is what tells server-side to associate the radio buttons to the viewmodel property. Also, doesn't the expression already tell what to bind the radiobutton to (ie the hiddenfor is not necessary)?
@model Student
@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")@Html.HiddenFor(model => model.Gender)
-
Hi, I'm having a hard time finding a simple enough (ELI5) direct answer to on here and the interwebz If I have the following html fragment on a razor page. How does the clicked button bind to the viewmodel Gender property (transfer data to/from viewmodel property and radiobutton input element)? If I understand it correctly, this binding happens server-side after a POST. This fragment below would have been inside a form, so ALL (male, female in this case) the radio button input types will get sent together with the hidden element. The expression parameters is what tells server-side to associate the radio buttons to the viewmodel property. Also, doesn't the expression already tell what to bind the radiobutton to (ie the hiddenfor is not necessary)?
@model Student
@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")@Html.HiddenFor(model => model.Gender)
RadioButtonFor
renders an<input type="radio">
with thename
set to the property name, and the value set to the specified value. If the model property matches the specified value, then the radio button will bechecked
. <input type="radio"> - HTML: HyperText Markup Language | MDN[^] When the form is submitted, the name and value of the checked radio button (if any) will be sent to the server, and the model binder will use it to populate the property. Adding the extraHiddenFor
for the same property should not be necessary.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer