[英]Dynamically creating controls asp.net C#
我有一个网站,您可以在其中进行多项选择测验。 测验中每个问题可能有1到5个可能的答案。 我在弄清楚如何根据有多少个答案来动态地制作测验控件时遇到了麻烦。 我可以轻松获得答案的数量。 因此,如果有3个答案,我需要生成3个文本框(只读)和相应的单选按钮列表。 然后,当用户按下按钮时,将提交数据并加载下一个问题。 我正在尝试使用C#来完成所有这些工作。
我曾经做过完全一样的事情,但是动态地只创建文本框。我正在复制代码(有点忙,现在要进行更改),请根据需要进行编辑:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</script>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
function GetDynamicTextBox(value)
{
return '<input name = "DynamicTextBox" class="dynamic" type="text" value = "' + "mymonthname" + '" />' +
'<input name = "DynamicTextBox1" class="dynamic" type="text" value = "' + "myYearname" + '" />' +
'<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox()
{
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div)
{
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
// function RecreateDynamicTextboxes() {
// var values = "vishal";
// if (values != null) {
// var html = "";
// for (var i = 0; i < values.length; i++) {
// html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
// }
// document.getElementById("TextBoxContainer").innerHTML = html;
// }
// }
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="TextBoxContainer" style="text-align: center;" class="step">
</div>
<div>
<div style="text-align: center;" id="setPrinteraxcis1">
<input id="btnAdd" type="button" value="Add" onclick="AddTextBox()" class="ANPClass" />
</div>
</div>
</form>
</body>
并访问值,您需要在.cs中编写以下代码”
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues == null || textboxValues.Length == 0)
{
string empty = "true";
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
this.Values = serializer.Serialize(textboxValues);
foreach (string textboxValue in textboxValues)
{
MultipleId.Add(textboxValue);
}
}
其中MultipleId是一个arraylist:
public ArrayList MultipleId = new ArrayList();
PS我读了您的要求,基于一些标准,然后可以在AddTextbox方法中使用计数器并循环创建所需数量的文本框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.