How to use strongly typed HTML helpers with null types?

I want to use strongly typed HTML helpers in ASP.NET MVC 2 with a property of my model that is Nullable<T> .

Model

 public class TicketFilter { public bool? IsOpen { get; set; } public TicketType? Type{ get; set; } // TicketType is an enum // ... etc ... } 

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

However, using helpers in this way throws an ArgumentNullException - the second parameter cannot be null. Instead of null I tried to use new bool?() / new TicketType? as well as String.empty . All of them lead to the same exception. How can I get around this and bind the control to a null value?

+7
nullable asp.net-mvc html-helper asp.net-mvc-2
source share
3 answers

Try the following:

 <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> 
+7
source share

Darin answers correctly, but does not select the correct switch when the property is null. The following code will fix this ...

 <%: 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 
+4
source share

I believe you should use the RadioButtonListFor HTML helper. Take a look at this SO post .

0
source share

All Articles