21

我试过这样做,但这只会显示单选按钮,旁边没有文字..

<% foreach (string s in Html.RadioButtonList("rbl")) {%>
    <% =s %>
<% } %> 
4

6 回答 6

13

Elijah Manor在 ASP.NET MVC 1.0 中写过同样的问题:

ASP.NET MVC Html.RadioButtonList 蓝调

他决定遍历他的 DataSource 并创建单独的 Html.RadioButton 和 Label 组合。

<!-- After using and looking at the code for the Html.RadioButtonList in the ASP.NET MVC 1.0 RTM codebase, I'm not sure how it is supposed to be useful. It only outputs the actual input radio button and doesn't render any corresponding labels. To get around this I ended up writing a foreach creating individual Html.RadioButton and labels -->
<%
var radioButtonList = new SelectList(new List<ListItem> {
    new ListItem { Text = "Current", Value="false", Selected=true },
    new ListItem { Text = "Other", Value="true"}}, "Value", "Text", "false");
var htmlAttributes = new Dictionary<string, object> {
    { "class", "radioButtonList" },
    { "onclick", "if(eval(this.value)) { $('#tblDate').show('slow'); } else { $('#tblDate').hide('slow'); }" }
};
foreach (var radiobutton in radioButtonList) { %>
    <%=Html.RadioButton("rblDate", radiobutton.Value, radiobutton.Selected, htmlAttributes)%>
    <label><%=radiobutton.Text%></label>
<% } %>
于 2009-04-02T20:22:48.007 回答
9

它曾经在预览中,但已被删除。

如果您在期货中找不到它,请尝试这样的事情

<% foreach (Model model in Models))
   {
%><%= String.Format("<input type=\"radio\" value=\"{0}\" name=\"{1}\" id=\"{2}\"><label for=\"{2}\">{3}</label>",
        model.ID, "fieldName", model.modelID, model.Name)  %><br />
<% } %>
于 2009-01-04T02:16:35.627 回答
7

如果是我,我会使用一系列静态 HTML 元素。我知道有些人考虑做这样的回归到 ASP 时代,但它简化了 IMO 的事情,最终形成了一个更可靠和可预期的 [所以我编造了一个词] GUI。

于 2008-12-09T18:21:42.460 回答
6
@{
    var radioButtonList = new SelectList(new List<ListItem> {
    new ListItem { Text = "1", Value="true", Selected=true },
    new ListItem { Text = "2", Value="false"},
    new ListItem { Text = "3", Value="false"},
    new ListItem { Text = "4", Value="false"},

    }, "Value", "Text", "false");

    var htmlAttributes = new Dictionary<string, object> {
    { "class", "radioButtonList" },
    { "onclick", "if(eval(this.value)) { $('#tblDate').show('slow'); } else { $('#tblDate').hide('slow'); }" }
};    
            }

@foreach (var radiobutton in radioButtonList) { 

  @Html.RadioButtonFor(m => m.ContactDepartment,  @radiobutton.Text) @radiobutton.Text

    <br/>
}
于 2012-08-30T05:37:12.623 回答
1

请参阅 Daniel Gidman 的好帮手,2012 年 6 月 14 日, 在这里。他为 MVC 中的 RadioButtonList 创建了一个不错且完美的助手。

于 2013-07-27T07:21:05.123 回答
-1

查看codeplex 上MVC 源代码中提供的 MVC Futures DLL。其中有一个 HtmlHelper 扩展来呈现 RadioButton 列表。它可以在 ViewData 中自动呈现 SelectList,或者您可以显式传递它。有几种重载可满足不同的需求。

于 2008-12-10T04:28:16.323 回答