由于Web的"无状态"本质,ASP.NET (Web Forms)项目动态加载用户控件需要注意一些问题:
1. 在页面的每次Postback,都要重新创建动态加载的用户控件
2. 若需要维护动态用户控件的状态(ViewState)或者事件,在每次加载时,使用相同的ID。
MSDN上提供了一种参考的方式,override页面的LoadViewState方法,因为该方法调用是在page_load事件之前,它可以保证这些动态控件在事件处理函数里面是可用的。下面是一个很简单的例子,例子很简单,页面上动态添加10个textbox,在viewstate里面保存一个标志位,表示是否动态添加了这些控件,在LoadViewState函数里进行判断,如果有这个标志,则重新加载这些控件。
3,下面是一个例子:
public partial class LoginPage : System.Web.UI.Page
{
HtmlInputText username;
HtmlInputPassword pwd;
HtmlInputButton submit;
HtmlInputButton cancel;
HtmlGenericControl show;
protected void Page_Load(object sender, EventArgs e)
{
username = new HtmlInputText("text");
pwd = new HtmlInputPassword();
submit = new HtmlInputButton("submit");
submit.Value = "提交";
submit.ServerClick += new EventHandler(submit_ServerClick);//绑定事件
cancel = new HtmlInputButton();
cancel.Value = "取消";
show = new HtmlGenericControl("span");
HtmlTable table = new HtmlTable(); //四行的表格
HtmlTableRow row1 = new HtmlTableRow();
HtmlTableRow row2 = new HtmlTableRow();
HtmlTableRow row3 = new HtmlTableRow();
HtmlTableRow row4 = new HtmlTableRow();
table.Rows.Add(row1); //行添加到表格里
table.Rows.Add(row2);
table.Rows.Add(row3);
table.Rows.Add(row4);
HtmlTableCell cell1 = new HtmlTableCell(); //定义单元格
cell1.ColSpan = 2;
row1.Cells.Add(cell1);
HtmlTableCell cell2 = new HtmlTableCell();
cell2.ColSpan = 2;
row2.Cells.Add(cell2);
HtmlTableCell cell3_1 = new HtmlTableCell();
HtmlTableCell cell3_2 = new HtmlTableCell();
row3.Cells.Add(cell3_1);
row3.Cells.Add(cell3_2);
HtmlTableCell cell4 = new HtmlTableCell();
cell4.ColSpan = 2;
row4.Controls.Add(cell4);
cell1.Controls.Add(username);
cell2.Controls.Add(pwd);
cell3_1.Controls.Add(submit);
cell3_2.Controls.Add(cancel);
cell4.Controls.Add(show);
HtmlGenericControl div = new HtmlGenericControl("div");
div.Style["Position"] = "absolute";
div.Style["left"] = "360px";
div.Style["top"] = "230px";
div.Style["border-style"] = "solid";
div.Style["border-width"] = "1px";
div.Style[HtmlTextWriterStyle.Padding] = "20px";
div.Controls.Add(table);
this.form1.Controls.Add(div);
}
void submit_ServerClick(object sender, EventArgs e)
{
if (username.Value == "张三" && pwd.Value == "123456")
{
Response.Redirect("http://www.baidu.com/");
}
else
{
show.Style["color"] = "red";
show.Style[HtmlTextWriterStyle.FontSize] = "14px";
show.InnerHtml = "用户名或密码错误!";
}
}
}