Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create an ASP.NET ImageButton that doesn't postback?

I'm trying to use the ImageButton control for client-side script execution only. I can specify the client-side script to execute using the OnClientClick property, but how do I stop it from trying to post every time the user clicks it? There is no reason to post when this button is clicked. I've set CausesValidation to False, but this doesn't stop it from posting.

like image 966
Giffyguy Avatar asked Apr 24 '10 04:04

Giffyguy


5 Answers

I know this problem has already been answered but a simple solution is to return false from the HTML onclick method (i.e. the ASPX OnClientClick method) e.g.

<asp:ImageButton ID="ImageNewLink" runat="server" 
 ImageUrl="~/images/Link.gif" OnClientClick="DoYourStuff(); return false;"  />

Returning false stops the browser from making the request back to the server i.s. stops the .NET postback.

like image 90
CodeClimber Avatar answered Nov 05 '22 08:11

CodeClimber


Here's one way you could do it without conflicting with the postback functioning of other controls:

Define your button something like this:

<asp:Button runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="alert('my client script here');my" />

The "my" ending in the handler for OnClientClick is a way to alias asp.net's __doPostBack client event that forces the postback; we simply override the behavior by doing nothing similar to this script:

<script type="text/javascript">

function my__doPostBack(eventTarget, eventArgument) {
    //Just swallow the click without postback of the form
}
</script>

Edit: Yeesh, I feel like I need to take a shower after some of the dirty tricks that I need to pull in order to get asp.net to do what I want.

like image 4
Pierreten Avatar answered Nov 05 '22 06:11

Pierreten


Another solution would be to define a PostBackUrl that does nothing

<asp:imagebutton runat="server" PostBackUrl="javascript:void(0);" .../>
like image 2
sarghir Avatar answered Nov 05 '22 07:11

sarghir


<image src="..." onclick="DoYourThing();" />
like image 1
John Gietzen Avatar answered Nov 05 '22 06:11

John Gietzen


Use a server side Image control

<asp:Image runat="server" .../>

Pretty sure you can add the client onclick event to that.

like image 1
mxmissile Avatar answered Nov 05 '22 06:11

mxmissile