简体   繁体   中英

.Net adds “__doPostBack” to javaScript onClick event… why?

Typically.NET handles the post back event on a button by making the button a type="submit":

<input type="submit" Text="Delete" />

However, I've recently bumped into a situation where .NET is handling the post back by making the input a type="button" and then adding a javaScript onClick event to do the "__doPostBack()" - so you end up with this:

<input type="button" onClick="__doPostBack(...);" />

The problem with this is trying to add confirmation messages to the click. So with the 2nd scenario, I end up with this:

<input type="button" onClick="return confirm('Are you sure?'); __doPostBack(...);" Text="Delete" />

Of course, in the above scenario the postback will never happen.

What I'm wondering is why .net chooses one scenario over there other and is there a way to prevent the 2nd?

Thanks

You need to have output like:

<input type="button" onClick="if(!confirm('Are you sure?')){return false};__doPostBack(...);" Text="Delete" />

By having it return if the confirm is true or false, you will not execute the postback. However if you only return on false, you should be fine.

The __doPostBack enables .net to add extra functionality such as client side validation checks. If it needs to do it that way, it will do.

In regard to your implementation, you could use the OnClientClick property of the button to set any additional scripts.

The answer to this is:

.Net uses __doPostBack(...) in the onClick event when working in an ajax scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM