我将使用Repeater 控件并将其绑定到将保存每个项目的数据的对象列表。您可以在后面的代码中轻松快速地完成这一切,验证将在客户端和服务器端都有效,换句话说,如果用户关闭 javascript,它将有效。
定义一个数据类,例如:
public class InputDataItem
{
public string Text { get; set; }
public InputDataItem()
{
}
public InputDataItem(string text)
{
this.Text = text;
}
}
和标记:
<asp:Repeater ID="rptInputs" runat="server">
<ItemTemplate>
<asp:TextBox ID="tbxInput" runat="server" Text='<%# Eval("Text") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rqfValidator" runat="server" ControlToValidate="tbxInput" ErrorMessage="* Required!"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
并绑定转发器并获取用户使用此代码输入的值
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
var data = new List<InputDataItem>();
for (int i = 0; i < 5; i++)
{
data.Add(new InputDataItem("Item " + i.ToString()));
}
rptInputs.DataSource = data;
rptInputs.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
var data = new List<InputDataItem>();
foreach (RepeaterItem rit in rptInputs.Items)
{
Control cnt = rit.FindControl("tbxInput");
if (cnt != null && cnt is TextBox)
data.Add(new InputDataItem((cnt as TextBox).Text));
}
/// here you have list of POCO objects filled with user input
}
}