Thursday, April 19, 2012

Data Binding to RadioButton in a View in MVC

This article is to provide information for how to do a data binding of a RadioButton (or group of them) in the View.

For example, you have Gender field in your model with two obvious options - Male, and Female.

What we really want to achieve is -
a. when a controller action invokes a view (with its model), it should correctly select the appropriate radio button from underlying model,
b. when a user changes the selection of radio button it should correctly update underlying model.

This is for what binding is needed.
For controls, such as TextBox, Label, etc, binding is quite straightforward using TextBoxFor, LabelFor, etc helpers.
But for controls such as RadioButton, CheckBox, etc, it's little bit different as below:

The below example is using RazorView engine.

@Html.RadioButtonFor(m => m.Gender, "Male", Model.Gender == "Male" ? new { Checked = "checked"} : null )
Male


@Html.RadioButtonFor(m => m.Gender, "Female", Model.Gender == "Female" ? new { Checked = "checked"} : null )
Female

Here, Checked is an HtmlAttribute for Checked state of RadioButton/ CheckBox
@Html.RadioButtonFor will show only RadioButton without its label, and for that purpose we have written Male, and Female after each Helpers.

6 comments:

  1. 10Q! but what about server side using pure sql insert statemnt

    ReplyDelete
  2. inserting radiobuttonFor value using native sql insert query in mvc 3 or 4

    ReplyDelete
    Replies
    1. inserting radiobuttonFor value into sql server 2008 express using native sql insert query in mvc 3 or 4

      Delete

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive