问题
I am generating dynamic html controls. The controls are being generated on Init, after the user has caused a postback by pressing a button. However, he needs to press it twice so that the controls are generated. How can I fix this? Code:
protected override void OnInit(EventArgs e)
{
if (Page.IsPostBack)
{
if (Session["id"] != null)
{
string id= Session["id"].ToString();
GenerateDynamicControls(id);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
Session["id"] = null;
}
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text;
Session["id"] = id;
}
回答1:
There is no need to use session for these purposes. Plus your code might fail after subsequent postbacks.
protected override void LoadViewState(object state)
{
base.LoadViewState(state);
var id = this.ViewState["DynamicControlGeneration"] as string;
if (id != null)
GenerateDynamicControls(id);
}
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text;
this.ViewState["DynamicControlGeneration"] = id;
GenerateDynamicControls(id);
}
回答2:
Session["id"]
is set to null on page load. When the page is posted back after button click, the OnInit
method is called first and it get the value of Session["id"]
as null
. After that the button click event is executed and Session["id"]
is set. So when you click the button second time the OnInit
has the value other than null
for Session["id"]
and your code is executed on the second click.
回答3:
Call GenerateDynamicControls(id); when button is clicked. That way you will have your controls on first click. And when page reloads they will be recreated in OnInit.
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text;
Session["id"] = id;
GenerateDynamicControls(id);
}
回答4:
Try this,
protected override void OnInit(EventArgs e)
{
if (Page.IsPostBack)
{
string id = Request.Form[TextBox1.ClientID].ToString();
GenerateDynamicControls(id);
}
}
来源:https://stackoverflow.com/questions/15496748/asp-net-button-needs-to-be-fired-twice