关于c#:在aspx中动态生成许多单选按钮

Generating a number of radio buttons dynamically in aspx

我有一个用于显示问题的视图和几个表示该问题可能答案的单选按钮。可能的答案数量随每个问题而变化,因此我需要找到一种动态生成单选按钮的方法。我是aspx语法的新手,并且不确定如何执行此操作,即如何显示在以下HTML脚本中创建的单选按钮的集合?使用RadioButtonList会更好吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<UncleBobWebService.Models.MultipleChoiceQuestion>" %>

<!DOCTYPE html>

<html>
  <head id="Head1" runat="server">
    Application
    <link href="/Theme/UncleBobTheme.css" rel="Stylesheet" />
    <script lang="cs" runat="server">

        protected void Page_Load(Object o, EventArgs e)
        {
            int count = Model.PossibleAnswers.Count;
            List<RadioButton> radioButtons = new List<RadioButton>();

            for (int i = 0; i < count; ++i)
            {
                RadioButton button = new RadioButton();
                button.ID ="1";
                button.GroupName ="answers";
                button.Text = Model.PossibleAnswers[i+1].TheAnswer;
                button.Checked = false;
                radioButtons.Add(button);
            }
        }

     
  </head>

<body>
    Question
   
        <form id=form1 runat=server action="/ApplicantApply/FormAction">
       
           
                <%= Html.DisplayFor(Model => Model.Question) %>

                <!-- How to display the radiobutton list here instead of below? -->
                <input type="radio" id="yesAnswer" name="yes" value="Yes">Yes<br />
                <input type="radio" id="noAnswer" name="no" value="No">No<br />
           
       
        <input type="submit" name="submit" value="Previous" />
        <input type="submit" name="submit" value="Next" />
        </form>
   
</body>

</html>

您正在将Asp.net WebForm示例代码与Asp.net MVC视图混合。您不想在MVC中使用Page_Load或任何Asp.net服务器控件。您想使用Html.RadioButton()

1
2
3
4
5
6
            <%= Html.DisplayFor(Model => Model.Question) %>

            <% for (var i=i; i<=Model.PossibleAnswers.Count(); i++) %>
            <label><%= Html.RadioButtonFor(m => m.PossibleAnswers[i],"Yes")> %> Yes</label>
            <label><%= Html.RadioButtonFor(m => m.PossibleAnswers[i],"No")> %> No</label>
            <% } %>

这些东西被asp.net称为Html Helpers。您可以用谷歌搜索该术语的示例。它们存在于大多数常见的表单元素中。


似乎您正在混合ASP.NET


在页面上显示答案和问题。但是问题答案显示选项类型明智,选项类型为多人选择单人回答,多人回答多人选择,图像日期。如果将答案表选项类型字段设置为1,则在在gridview中明智地使用单选按钮,以便在asp.net

中创建此页面


您可以使用以下链接。

http://www.developerscode.com/2011/02/how-to-create-dynamic-registration-form.html

动态创建的radiobuttonlist

http://csharp-guide.blogspot.in/2012/05/adding-radiobutton-options-dynamically.html

http://forums.asp.net/t /1192583.aspx/1

http://www.codeproject.com/Questions/360219/radio-button-dynamic-creation

ASP.net创建动态单选按钮列表

希望这会对您有所帮助。