Bind model to radio buttons
asp.net-mvc, razor
Solution
Looking at your code, there maybe a better way overall. First, create an enumeration of the radio button types/values that you have available:
public enum DateEnum {
Today,
Yesterday,
DateRange
}
Then modify your `DateModel` to use that enum
public class DateModel
{
public DateEnum SelectedDate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
Lastly, update your view that your binding with to use the enum while using `RadioButtonFor()`
<tr>
<td>
@Html.RadioButtonFor(x => x.SelectedDate, DateEnum.Today) Today
</td>
</tr>
<tr>
<td>
@Html.RadioButtonFor(x => x.SelectedDate, DateEnum.Yesterday) Yesterday
</td>
</tr>
<tr>
<td>
@Html.RadioButtonFor(x => x.SelectedDate, DateEnum.DateRange) Call Date Range
</td>
</tr>
Then on the form submission, you would look at the `SelectedDate` to determine which radio button the user has selected.
Problem
Hi I have a report model that needs a date. he date can either be Today, Yesterday or a date range. ``` public class DateModel { public bool Today { get; set; } public bool Yesterday { get; set; } public bool DateRange { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } } ``` This model is bound to a view. radio buttons for Today,Yesterday,DateRange and text boxes for Start and End date. ``` <tr> <td> @Html.RadioButton("SelectedDate", "Yes", true, new { postData= "Today" }) Today </td> </tr> <tr> <td> @Html.RadioButton("SelectedDate", "No", false, new { postData= "Yesterday" }) Yesterday </td> </tr> <tr> <td> @Html.RadioButton("SelectedDate", "No", false, new { postData= "CallDateRange" }) Call Date Range </td> </tr> ``` When the view is posted back, how can I get what radio button was selected?