我有一个名为“answers”的调查回复字符串数组。
string[] answers = new string[10] {"Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y"};
我知道如果我像这样为每个索引创建一个新字符串:
string answer1 = answers[0]
我可以将 <%=answer1%> 放在 HTML/ASPX 页面中,它会按原样显示“Y”。但是,我的数组将包含 50 个以上的项目(尽管项目的数量不会改变)。
一种方法是创建 50 个变量并分别引用它们,但说实话......
这是我的 <body>
;)(或者至少我希望它看起来像什么。)
<body>
<div class="container">
<asp:Panel ID="pnlResults1" runat="server">
<div class="section z-depth-2 blue-grey lighten-5">
<table style="width: 25%" align="center">
<tr>
<td><b>Question 1:</b></td>
<td><%=answer1%></td>
</tr>
<tr>
<td><b>Question 2</b></td>
<td><%=answer2%></td>
</tr>
<tr>
<td><b>Question 3</b></td>
<td><%=question3%></td>
</tr>
<tr>
<td><b>Question 4</b></td>
<td><%=question4%></td>
</tr>
<tr>
<td><b>Question 5</b></td>
<td><%=question5%></td>
</tr>
<tr>
<td><b>Question 6</b></td>
<td><%=question6%></td>
</tr>
</table>
</div>
</asp:Panel>
</div>
..表格行将继续计数。基本上,我想在表格中显示我的 50 多个调查回复,而不必为每个数组索引创建一个字符串。
我正在考虑在 html/aspx 中为答案创建文本框,并使用 foreach 循环遍历每个文本框并在遍历答案时添加答案[],但我不确定如何遍历答案.
类似于(伪代码)
int counter = 0;
foreach(Control c in Panel){
if(c is Text)
Text.setText(answers[counter]);
counter++;
}
如有任何帮助,我们将不胜感激。谢谢!
最佳答案
将其放入您的 *.aspx 文件中:
<div class="container">
<div class="section z-depth-2 blue-grey lighten-5">
<asp:Repeater ID="rptResults1" runat="server">
<HeaderTemplate><table style="width: 25%" align="center"></HeaderTemplate>
<ItemTemplate>
<tr>
<td><strong>Question <%# Container.ItemIndex + 1 %>:</strong></td>
<td><%# Container.DataItem %></td>
</tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:Repeater>
</div>
</div>
然后将其放入您的代码隐藏中:
string[] answers = new string[10] {"Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y"};
rptResults1.DataSource = answers;
rptResults1.DataBind();
如果您真的想要,您可以将其放入您的标记中:
<div class="container">
<div class="section z-depth-2 blue-grey lighten-5">
<table style="width: 25%" align="center">
<%
string[] answers = new string[10] {"Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y"};
string rowTemplate = "<tr><td><b>Question {0}:</b></td><td>{1}</td></tr>\n";
for (int i = 0; i<answers.Length;i++)
{
Response.Write(string.Format(rowTemplate, i+1, answers[i]));
}
%>
</table>
</div>
</div>
不过,我不推荐第二种选择。如果它对您有吸引力,请尝试了解 Razor syntax相反,甚至使用 ASP.Net MVC 代替 Web 窗体。
关于c# - 如何将数组从 C# 代码隐藏显示到 ASPX 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709928/