2012-05-29 60 views
45

局部視圖 我使用這樣的文本框。我怎樣才能生成單選按鈕,並在表單集合中獲得所需的值爲YES/NO True/False)????????????????????????????目前,如果我爲以下選擇任何值,「ABC」將爲空。MVC剃刀單選按鈕

<label>@Html.RadioButton("ABC", @Model["ABC"])Yes</label> 
    <label>@Html.RadioButton("ABC", @Model["ABC"])No</label> 

控制器

 public int Create(int Id, Dictionary<string, string> formValues) 
     { 
     //Something Something 
     } 
+0

顯示你的操作方法代碼。 –

+2

[ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC]的可能重複(http://stackoverflow.com/questions/2559208/asp-net-mvc-yes-no-radio-buttons-with-strongly -bound-model-mvc) –

回答

57

爲了爲多個項目做這個做這樣的事情:

foreach (var item in Model) 
{ 
    @Html.RadioButtonFor(m => m.item, "Yes") @:Yes 
    @Html.RadioButtonFor(m => m.item, "No") @:No 
} 
+1

我打電話給我的所有部分視圖傳遞@model Dictionary 我需要一種方法來爲單選按鈕中的選定值返回(True,False)或(Yes,No)。 – Nanu

+1

@KirkWoll他的代碼不會綁定到'Dictionary '(如他的模型所述)。根據Yes No的迴應,bool可能是最好的,如果你不允許選擇,那麼可以使用Nullable bool。 – mattytommo

+0

@KirkWoll檢查我的更新的編輯,我原本以爲他只是想要一個選項的是否,因此建議一個布爾。 – mattytommo

13

我解決this同樣的問題,所以回答。

基本上它將單選按鈕綁定到強類型模型的布爾屬性。

@Html.RadioButton("blah", !Model.blah) Yes 
@Html.RadioButton("blah", Model.blah) No 

希望它有幫助!

8
<label>@Html.RadioButton("ABC", "YES")Yes</label> 
<label>@Html.RadioButton("ABC", "NO")No</label> 
22

簡單:

<label>@Html.RadioButton("ABC", True)Yes</label> 
    <label>@Html.RadioButton("ABC", False)No</label> 

但你應該總是使用強類型的模型由卡丘的建議。

1

這對我有用。

@{ var dic = new Dictionary<string, string>() { { "checked", "" } }; } 
@Html.RadioButtonFor(_ => _.BoolProperty, true, (@Model.BoolProperty)? dic: null) Yes 
@Html.RadioButtonFor(_ => _.BoolProperty, false, ([email protected])? dic: null) No 
11

我的方式做到了這一點,如:

@Html.RadioButtonFor(model => model.Gender, "M", false)@Html.Label("Male") 
    @Html.RadioButtonFor(model => model.Gender, "F", false)@Html.Label("Female") 
1
<p>@Html.RadioButtonFor(x => x.type, "Item1")Item1</p> 
<p>@Html.RadioButtonFor(x => x.type, "Item2")Item2</p> 
<p>@Html.RadioButtonFor(x => x.type, "Item3")Item3</p> 
1
​​
+0

請解釋您的解決方案。 –