asp.net-mvc - 如何使用可空类型的强类型 HTML 助手?

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

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

最佳答案

试试这个:

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

关于asp.net-mvc - 如何使用可空类型的强类型 HTML 助手?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027875/

相关文章:

ASP.NET MVC 4 AJAX 提交表单不起作用

asp.net-mvc - MVC 3 从 web.config 中的 AppSettings 获取值

asp.net-mvc-2 - 如何在 ASP.NET MVC2 中路由带下划线的小写 URL ('questions/add_to_favorites/123')?

asp.net - 问题: zip files in mvc

c# - ASP.NET 5 Beta 7 (Web Tools 2015 Beta7) - wwwroot/index.html 未提供

c# - asp.net mvc c#中的Json序列化

asp.net-mvc - 如何使用 ASP.Net MVC 创建 Multi-Tenancy 应用程序?

java - 如何避免 Java 中的多个 If 语句?

c# - 指定的转换对日期选择器无效

asp.net - 将可为空的 int 绑定(bind)到 asp :TextBox