Bra*_*bby 7 asp.net-mvc html-helper nullable asp.net-mvc-2
我想在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 ...
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
但是,以这种方式使用帮助程序会抛出ArgumentNullException- 第二个参数不能为null.而不是null,我尝试使用new bool?()/ new TicketType?以及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>
Run Code Online (Sandbox Code Playgroud)