Asp.net

mvc 綁定/發布布爾到單選按鈕

  • September 16, 2015

我的模型中有一個帶有 NULLABLE 布爾值的列。現在在我的視圖(用於編輯)上,我想將其綁定到兩個單選按鈕:是和否。如果值為空,則只需取消選中這兩個單選按鈕。我該怎麼做呢?

謝謝。

一旦您選擇了一個單選按鈕,就沒有辦法取消選擇它(作為使用者)。我建議如果你真的需要一個三值結果,你有三個單選按鈕——是的,不,不在乎。

<%= Html.LabelFor( m => m.Foo ) %>
<%= Html.RadioButtonFor( m => m.Foo, "true" ) %> Yes
<%= Html.RadioButtonFor( m => m.Foo, "false" ) %> No
<%= Html.RadioButtonFor( m => m.Foo, string.Empty ) %> Don't Care
<%= Html.ValidationMessageFor( m => m.Foo ) %>

我可以晚點閱讀這篇文章,但是這是我的解決方案,它也處理設置值。這使用了一個編輯器模板。您需要指定編輯器模板名稱。我叫我的’NullableBool'

@model bool?

@{

Layout = null;

IDictionary<string, object> yesAttributes = new Dictionary<string, object>();
IDictionary<string, object> noAttributes = new Dictionary<string, object>();
IDictionary<string, object> naAttributes = new Dictionary<string, object>();

if (Model.HasValue)
{
   if (Model.Value)
   {
       yesAttributes.Add("checked", "checked");
   }
   else
   {
       noAttributes.Add("checked", "checked");
   }
}
else
{
   naAttributes.Add("checked", "checked");
}
}

@Html.RadioButtonFor(m => m, "true", yesAttributes) Yes`

@Html.RadioButtonFor(m => m, "false", noAttributes) No`

@Html.RadioButtonFor(m => m, string.Empty, naAttributes) N/A`

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