2011-03-05 103 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