MVC和RadioButtonList

dev*_*all 19 asp.net-mvc html.radiobuttonlist

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

<% foreach (string s in Html.RadioButtonList("rbl")) {%>
    <% =s %>
<% } %> 
Run Code Online (Sandbox Code Playgroud)

Zac*_*son 12

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

ASP.NET MVC Html.RadioButtonList Blues

他决定遍历他的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>
<% } %>
Run Code Online (Sandbox Code Playgroud)


cco*_*ook 8

它曾经在预览中但它被删除了.

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

<% 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 />
<% } %>
Run Code Online (Sandbox Code Playgroud)


bra*_*ter 7

如果是我,我会使用一系列静态HTML元素.我知道有些人会考虑对ASP时间做这样的回归,但它简化了IMO的事情,最终使得更加可靠和可预期[所以我制定了一个词] GUI.


小智 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/>
}
Run Code Online (Sandbox Code Playgroud)