嗨,我有一个需要约会的报告模型。他的日期可以是今天,昨天或日期范围。
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; }
}
此模型绑定到视图。今天,昨天,DateRange和开始日期和结束日期的文本框的单选按钮。
<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>
当回发视图时,如何才能获得选择的单选按钮?
答案 0 :(得分:10)
查看您的代码,总体来说可能有更好的方法。首先,创建一个可用的单选按钮类型/值的枚举:
public enum DateEnum {
Today,
Yesterday,
DateRange
}
然后修改您的DateModel
以使用该枚举
public class DateModel
{
public DateEnum SelectedDate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
最后,更新您的绑定视图,以便在使用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>
然后在表单提交上,您将查看SelectedDate
以确定用户选择了哪个单选按钮。
答案 1 :(得分:2)
您可以像这样修改模型:
public enum DateType {
Today,
Yesterday,
DateRange
}
public class DateModel
{
public DateType DateType { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
并在视图中使用它:
@model DateModel
@Html.BeginForm("ProcessForm") {
@* Populate radio *@
@Html.RadioButtonFor(x => x.DateType , DateType.Today) Today
@Html.RadioButtonFor(x => x.DateType , DateType.Yesterday) Yesterday
@Html.RadioButtonFor(x => x.DateType , DateType.DateRange) DateRange
@* Range *@
@Html.TextBoxFor(x => x.StartDate ) Start date
@Html.TextBoxFor(x => x.EndDate ) End date
<input type="submit" />
}
将模型传递给控制器
public ActionResult ProcessForm(DateModel model) { // here you get model from form
// ..
}