【问题标题】:Bind model to radio buttons将模型绑定到单选按钮
【发布时间】:2013-06-29 21:24:22
【问题描述】:

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

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>

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

【问题讨论】:

  • 这在很大程度上取决于你如何渲染你的单选按钮,以及视图是如何绑定的。您可以使用单选按钮的区域编辑您的帖子吗?
  • @StevenVondruska 已更新。

标签: asp.net-mvc razor


【解决方案1】:

查看您的代码,总体上可能有更好的方法。首先,创建一个可用的单选按钮类型/值的枚举:

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

【讨论】:

  • 谢谢。但 selectedDate 值始终是 DateRange?是否有一个原因?我哪里做错了?谢谢
  • 我在我的机器上设置了一个小型测试项目,使用代码并且它可以工作。我将使用浏览器或 Fiddler 中的开发人员工具查看浏览器发布的内容,以查看浏览器向应用程序报告的内容。还要确保页面上没有其他具有相同名称/值的表单元素。
  • 谢谢史蒂夫。如何使用此语法更改名称?
  • 唯一的方法是更改​​DateMode; 上的SelectedDate 属性。如果您使用 Javascript 将名称从“SelectedDate”更改为“Foobar”或手动设置它,MVC 将不知道如何将表单帖子自动绑定到 DateModel
【解决方案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
   // .. 
}

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 2020-01-19
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多