Button inside server control doesn't render onclick="__doPostback"
I'm developing a Asp.net server control (inherited from DataBoundControl) and I have just one button inside it for now which is created in CreateChildControls override. Even though this button have Click event assigned in rendered page the button don't have onclick event with __doPostback or something similar. Am I missing something?
public class FileList : DataBoundControl, INamingContainer
{
protected override void CreateChildControls()
{
// Add button
btnAddFile = new System.Web.UI.WebControls.Button();
btnAddFile.ID = "btnAddFile";
btnAddFile.Click += btnAddFile_Click;
btnAddFile.CssClass = "Button";
btnAddF开发者_如何学编程ile.CausesValidation = false;
Controls.Add(btnAddFile);
}
void btnAddFile_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
I found the answer myself, sollely by chance. And it's very veird. Button
has an attribute UseSubmitBehavior
which by default is true
meaning browser submit behaviour is used by default. Setting this value to false
solves the issue.
However if it always have been like this I would noticed that. So I went and created a button inside ASCX, and the value was false
. So somehow defaults are different depending on how you created a button. This is strange.
There shouldn't be any onclick event.... <asp:Button>
is parsed to ordinary HTML submit button, with name equal to the button ID and value equal to the button text.
Try creating the button only when not in post back, hopefully it will solve your problem:
if (!Page.IsPostBack)
{
// Add button
btnAddFile = new System.Web.UI.WebControls.Button();
btnAddFile.ID = "btnAddFile";
btnAddFile.Click += btnAddFile_Click;
btnAddFile.CssClass = "Button";
btnAddFile.CausesValidation = false;
Controls.Add(btnAddFile);
}
精彩评论