I have explicitly added __doPostBack() on Button onclientClick event .
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="__doPostBack('Button1','')"/>
When I am clicking the button the Page_Load is calling twice.
But if I am adding below code inside page load ,page load is calling only once on button click.
Button1.Attributes.Add("onClientClick", "__doPostBack('Button1','')");
Again if i add with return false it is giving me it calling only once page load on click
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="__doPostBack('Button1','');return false;"/>
and return true is giving me again twice page load ,but adding return true or false in attribute.add code is giving the same result ,only one page load call.
Button1.Attributes.Add("onClientClick", "__doPostBack('Button1','');return true;");
I am not able to understand what is going on exactly when I tried to add __doPostBack in different way.
Please help.
Thanks
By placing the OnClientClick, then the asp.net render the onlick function on client size with both your code and a doPostBack.
So its called 2 times because one its called by self, and one because you added.
The answers of Aristos and user449689 are correct : you have a double postback because an ASP.NET button always do postback (so the OnClientClick is useless as it triggers another postback before).
When you return true (or don't return anything) from OnClientClick, you don't prevent the JavaScript onClick event of the button (i.e. the button still gets clicked and trigger _doPostBack followed by the normal postback). If you return false, the onClick event is cancelled (i.e. the button is not really clicked, so only _doPostBack is triggered). That's JavaScript behavior.
The OnClientClick attribute is rendered as "onClick" in the HTML code (when this attribute is on an ASP.NET button). Your statement...
Button1.Attributes.Add("onClientClick", "__doPostBack('Button1','');return true;");
...is not valid HTML as it renders "onClientClick" which is not a JavaScript event (i.e. _doPostBack is never triggered but the usual postback is). Attributes property is used to add straight HTML attributes (no rewrite from .NET) to the final rendering of the button.
My advice : don't call _doPostBack unless you have not found any other alternative to trigger a post back.
In the sample you provided, the OnClientClick attribute is completely redundant.
I hope I was clear enough (my English is not great).
A Button already do a PostBack, so why do you need to call it from client side?
Anyway, the page_load in your case is called twice I think because one time is done by the OnClientClick, the second time server side.
You could try viewing the rendered output (i.e. access your ASPX page in your browser and view page source) and seeing what the resulting HTML/Javascript looks like. Perhaps the __doPostBack
is being called twice.