我创建了一个允许用户动态添加更多文本框的网络表单。现在,当单击按钮添加另一个字段时,它会回发到自身。在 Pre_Init 中添加控件。但是,当页面自行重建时,文本框名称每次都不同,因此数据不会在每次回发时保留。
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPage master = this.Master; //had to do this so that controls could be added.
createNewTextField("initEnumValue",true);
RecreateControls("enumValue", "newRow");
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
//Response.Write(cnt.ToString() + "<br>");
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "newRow")
{
createNewTextField(ctrlID,false);
}
break;
}
}
}
}
}
protected void addEnum_Click(object sender, ImageClickEventArgs e)
{
int cnt = FindOccurence("enumValue");
createNewTextField("enumValue" + Convert.ToString(cnt + 1),false);
// Response.Write(cnt.ToString() + "<br>");
}
private void createNewTextField(string ID, bool button)
{
Response.Write(ID + "<br/>"); //this is where I'm getting different names each time there is a postback
if (ID != "initEnumValue") //create new line starting with the second tb.
{
LiteralControl newLine = new LiteralControl();
newLine.Text = "<br />";
this.plhEnum.Controls.Add(newLine);
}
TextBox newTb = new TextBox();
newTb.ID = ID;
this.plhEnum.Controls.Add(newTb);
if (button) //create the button only on the first one.
{
LiteralControl space = new LiteralControl();
space.Text = " ";
this.plhEnum.Controls.Add(space);
ImageButton imgbutton = new ImageButton();
imgbutton.ID = "addEnum";
imgbutton.ImageUrl = "~/images/add.png";
imgbutton.Click += new ImageClickEventHandler(addEnum_Click);
imgbutton.CausesValidation = false;
this.plhEnum.Controls.Add(imgbutton);
}
//endEnumRow();
//this.plhEnum.Controls.Add(newTb);
}
我已经尝试过这个解决方案如何从 ASP .NET MVC 中的动态生成控件中获取数据?