【问题标题】:How do I use the strongly-typed HTML helpers with nullable types?如何使用可空类型的强类型 HTML 助手?
【发布时间】:2011-04-30 23:36:10
【问题描述】:

我想在 ASP.NET MVC 2 中使用强类型 HTML 帮助器,我的模型的属性是 Nullable<T>

型号

public class TicketFilter {
    public bool? IsOpen { get; set; }
    public TicketType? Type{ get; set; } // TicketType is an enum
    // ... etc ...
}

查看 (HTML)

<p>Ticket status:
  <%: Html.RadioButtonFor(m => m.IsOpen, null) %> All
  <%: Html.RadioButtonFor(m => m.IsOpen, true) %> Open
  <%: Html.RadioButtonFor(m => m.IsOpen, false) %> Closed
</p>
<p>Ticket type:
  <%: Html.RadioButtonFor(m => m.Type, null) %> Any
  <%: Html.RadioButtonFor(m => m.Type, TicketType.Question) %> Question
  <%: Html.RadioButtonFor(m => m.Type, TicketType.Complaint) %> Complaint
  <!-- etc -->
</p>

但是,以这种方式使用帮助程序会引发ArgumentNullException——第二个参数不能为空。而不是null,我尝试使用new bool?()/new TicketType?String.empty。所有结果都导致相同的异常。如何解决此问题并将控件绑定到空值?

【问题讨论】:

  • 您希望单选按钮返回什么空值?
  • 我会想象一个空白字符串,甚至是“null”这个词。大概DefaultModelBinder 会知道在从表单值构建TicketFilter 以传递给我的操作方法时该怎么做,不是吗?

标签: asp.net-mvc asp.net-mvc-2 nullable html-helper


【解决方案1】:

试试这个:

<p>Ticket status:
  <%: Html.RadioButtonFor(m => m.IsOpen, "") %> All
  <%: Html.RadioButtonFor(m => m.IsOpen, "true") %> Open
  <%: Html.RadioButtonFor(m => m.IsOpen, "false") %> Closed
</p>
<p>Ticket type:
  <%: Html.RadioButtonFor(m => m.Type, "") %> Any
  <%: Html.RadioButtonFor(m => m.Type, "Question") %> Question
  <%: Html.RadioButtonFor(m => m.Type, "Complaint") %> Complaint
  <!-- etc -->
</p>

【讨论】:

  • 嗯,这很奇怪。我发誓我之前尝试过""string.Empty,但它抛出了异常,但现在它可以工作了!但是:当模型的属性为空时,不会检查任何单选按钮(我猜是因为"" != null)。我可以用一点 JS 来解决这个问题,但是有服务器端的解决方案吗?
  • 不幸的是,这不能在服务器端完成。这里的问题是您使用 null 来表示一个真实状态,即 All。因此,您使用可为空的布尔类型来表示四种可能的状态:打开、关闭、全部和无。因此,您可以使用具有 3 个值的可空枚举,而不是使用可为空的布尔值:打开、关闭和全部,如果属性为空,则不会选择三个单选按钮。 Type 属性也是如此:您可以使用 Any、Question 和 Compliant 值,这样您就不必在帮助程序中使用 null 或 string.Empty 作为值。
【解决方案2】:

Darin 的回答是正确的,但是当属性为 null 时没有选择正确的单选按钮。下面的代码将解决这个问题...

<%: Html.RadioButtonFor(m => m.Type, "", new { @checked = (Model.Type == null) }) %> Any
<%: Html.RadioButtonFor(m => m.Type, "Question") %> Question
<%: Html.RadioButtonFor(m => m.Type, "Complaint") %> Complaint

【讨论】:

    【解决方案3】:

    我相信您应该使用RadioButtonListFor HTML 助手。看看这个 SO post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多