Asp.net-Mvc

如何使用可空類型的強類型 HTML 助手?

  • October 30, 2013

我想在 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 ...
}

查看 (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>

但是,以這種方式使用幫助器會引發ArgumentNullException– 第二個參數不能為空​​。而不是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>

達林的回答是正確的,但是當屬性為空時沒有選擇正確的單選按鈕。以下程式碼將解決該問題…

<%: 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

引用自:https://stackoverflow.com/questions/4027875