2011-03-05 42 views
3

如何確保單選按鈕列表中的第一個選項被選中?如果它基於模型屬性,如果這是應用程序啓動時顯示的第一個頁面,它將如何設置?ASP.NET MVC中的默認radiobuttonlist Razor

這在webforms中很容易出現問題,但我不知道如何在MVC中做到這一點,並且在NET上似乎沒有任何地方顯示這是如何完成的。

這似乎並不工作:

@Html.RadioButtonFor(m => m.SearchType, true) Location 
@Html.RadioButtonFor(m => m.SearchType, false) Name 

我剛拿到這兩個單選按鈕未選中的?

回答

12
@Html.RadioButtonFor(x => x.Something, "radioValue", new { @checked = true }) 
5
@Html.RadioButtonFor(x => x.Something, "radioValue", new { @checked = "checked"}) 

,或者如果你是從模型

@Html.RadioButtonFor(x => x.Something, "radioValue", new { @checked = Model.checked}) 

,如果我們嘗試這樣的事情哪裏x.checked從數據庫綁定綁定即可。不管真假如何。檢查列表中的最後一個單選按鈕,其餘部分未被選中。

我們如何綁定數據庫中的單選按鈕列表並讓它工作正常?

+0

不能從LINQ表達外調用'x'。 – CalMlynarczyk 2012-02-03 14:37:54

+0

我的道歉,它假設是模型 – HaBo 2012-02-03 14:41:54

+0

@Habo您的問題將通過使用下面的GeorgeMR答案的語法來解決。 – 2014-01-02 09:25:38

3

這是我的解決方案:

@Html.RadioButtonFor(model => model.Coin , "Dollar", Model.Coin == "$" ? (new { @checked = "checked" }) : null) 
@Html.RadioButtonFor(model => model.Coin , "Euro", Model.Coin == "E" ? (new { @checked = "checked" }) : null) 
+1

任何理由或解釋將爲您的答案提供支持。 – 2012-10-22 01:23:17