views:

376

answers:

3

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.

+1  A: 
<image src="..." onclick="DoYourThing();" />
John Gietzen
That'd be perfect, except that this button is built dynamically on the server-side and needs to be a .NET object.
Giffyguy
You can always have an `asp:Literal` control on your page, and in your code behind dynamically set text to that, i.e.: `myLiteral.Text = "<img src=\"asdf\" onclick=\"DoYourThing();\" />";`
Jim Schubert
A: 

Use a server side Image control

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

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

mxmissile
+3  A: 

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.

Pierreten