加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何使用具有可空类型的强类型HTML帮助程序?

发布时间:2020-12-16 04:18:29 所属栏目:asp.Net 来源:网络整理
导读:我想在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) pTicket stat
我想在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.我试过使用新的bool?()/ new TicketType而不是null?以及String.empty.所有都会导致相同的异常.我该如何解决这个问题并将控件绑定到空值?

解决方法

试试这个:
<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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读