Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the strongly-typed HTML helpers with nullable types?

I want to use the strongly-typed HTML helpers in ASP.NET MVC 2 with a property of my model which 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 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?

like image 807
Brant Bobby Avatar asked Oct 26 '10 20:10

Brant Bobby


2 Answers

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>
like image 146
Darin Dimitrov Avatar answered Oct 06 '22 01:10

Darin Dimitrov


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
like image 28
wycleffsean Avatar answered Oct 05 '22 23:10

wycleffsean