Explicit __doPostBack()

此生再无相见时 提交于 2019-12-02 06:51:06

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!