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

泪湿孤枕 提交于 2019-11-28 13:34:10

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.

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.

Another solution would be to define a PostBackUrl that does nothing

<asp:imagebutton runat="server" PostBackUrl="javascript:void(0);" .../>
<image src="..." onclick="DoYourThing();" />

Use a server side Image control

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

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

Solution 1

<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="return false;"  />

OR Solution 2

<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg" 
OnClientClick="yourmethod(); return false;"  />

In addition (solution 2), your javascript method may be in this form

<script type="text/javascript">
    function yourmethod() {
    __doPostBack (__EVENTTARGET,__EVENTARGUMENT); //for example __doPostBack ('idValue',3);
    }
</script>

in code behind

protected void Page_Load(object sender, System.EventArgs e)
{
    if (this.IsPostBack) {
        string eventTarget = this.Request("__EVENTTARGET") == null ? string.Empty : this.Request("__EVENTTARGET");
        string eventArgument = this.Request("__EVENTARGUMENT") == null ? string.Empty : this.Request("__EVENTARGUMENT");
    }
}

This works Great for me:

Use OnClientClick to write your script and PostBackUrl="javascript:void(0);" to avoid postback.

<div class="close_but">
    <asp:ImageButton ID="imgbtnEChartZoomClose" runat="server" ImageUrl="images/close.png" OnClientClick="javascript:zoomclosepopup();" PostBackUrl="javascript:void(0);" />
    </div>

Use OnClientClick to write your script and PostBackUrl="javascript:void(0);" to avoid postback

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