I want to use the strongly-typed HTML helpers in ASP.NET MVC 2 with a property of my model which is Nullable<T>
.
public class TicketFilter {
public bool? IsOpen { get; set; }
public TicketType? Type{ get; set; } // TicketType is an enum
// ... etc ...
}
<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>
However, using the helpers in this way throws an ArgumentNullException
-- the second parameter cannot be null. Instead of null
, I've tried using new bool?()
/new TicketType?
as well as String.empty
. All result in the same exception. How can I work around this and bind a control to a null value?
Try this:
<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>
Darin's answer is correct, but doesn't select the correct radio button when the property is null. The following code will fix that...
<%: 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With