代码之家  ›  专栏  ›  技术社区  ›  Brant Bobby

如何使用可为空类型的强类型HTML帮助程序?

  •  7
  • Brant Bobby  · 技术社区  · 14 年前

    我想在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 . 所有这些都会导致相同的异常。如何解决此问题并将控件绑定到空值?

    3 回复  |  直到 11 年前
        1
  •  7
  •   Darin Dimitrov    14 年前

    试试这个:

    <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>
    
        2
  •  4
  •   wycleffsean    11 年前

    Darin的回答是正确的,但在属性为空时没有选择正确的单选按钮。以下代码将修复此问题…

    <%: 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
  •  0
  •   Community    7 年前

    我相信你应该使用 RadioButtonListFor HTML帮助程序。看看这个所以 post .