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?
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
I believe you should be using the RadioButtonListFor
HTML helper. Take a look at this SO post.
精彩评论