2

嗨,我有一个需要日期的报告模型。他的日期可以是今天、昨天或日期范围。

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; }
}

这个模型绑定到一个视图。今天,昨天,日期范围的单选按钮和开始和结束日期的文本框。

<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>

当视图被发回时,我怎样才能得到选择了哪个单选按钮?

4

2 回答 2

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以确定用户选择了哪个单选按钮。

于 2013-07-02T13:46:23.537 回答
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
   // .. 
}
于 2013-07-02T13:48:26.070 回答