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.
Subscribe to:
Post Comments (Atom)
Blog Archive
-
▼
2012
(49)
-
▼
April
(24)
- Get only Date part for SQL Server DateTime value
- Membership in ASP.NET MVC 4 (System.Web.Providers)
- Binding two or more types of objects (models) to s...
- Implement Custom Validation in ASP.NET MVC
- Simple client-side Validations using ASP.NET MVC
- Investigation: Values do not retain in model while...
- Data Binding to RadioButton in a View in MVC
- Investigation: SelectedIndexChanged not firing for...
- Investigation: ExecuteNonQuery() always returns -1
- Development and Deployment - Troubleshooting, Inve...
- Print Page Content to printer (or virtual print ou...
- Show long text in Tooltip
- Auto login into Team system with your authorized c...
- Visual Studio .NET - Some handy shortcuts
- Write custom events for User Controls in ASP.NET
- SQL Query to return each date of month in each dif...
- How to debug ASP.NET Windows Service
- FIX: Add a 32-bit SQL Server 2000 as a Linked serv...
- Difference between integer Cast and Convert in C#
- Optimizing SQL Code by replacing IF..ELSE with CAS...
- Check Authentication Mode in ASP.NET
- How to validate a page using Java script
- SQL Query - To search for a column (by column name...
- C#.NET - Difference between Convert.ToString(), .T...
-
▼
April
(24)
10Q! but what about server side using pure sql insert statemnt
ReplyDeleteinserting radiobuttonFor value using native sql insert query in mvc 3 or 4
ReplyDeleteinserting radiobuttonFor value into sql server 2008 express using native sql insert query in mvc 3 or 4
Delete
ReplyDeleteThanks for sharing this amazing blog
Dot Net Online Course
This was a lovelly blog post
ReplyDeleteNice blog thanks ffor posting
ReplyDelete