简体   繁体   中英

How to prevent postback while redirecting to a new page with LinkButton/ImageButton

<asp:ImageButton ID="ts" ImageUrl="ts.png" runat="server" CssClass="thumbnail" ClientIDMode="Static" OnClick="Client_Click" />
<asp:LinkButton ID="Lb4" runat="server" OnClick="Client_Click" CssClass="linkOff" Text="E"></asp:LinkButton>

Code-behind:

protected void Client_Click(object sender, EventArgs e)
{
    int k = this.Master.Client.ID;
    if (k > 0)
    {
        Response.Redirect("http://mypage.com" + this.Master.client.SelectedValue , "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10,left=0");
    }
    else
        Response.Redirect("http://mypage.edu" + this.Master.client.SelectedValue , "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10,left=0");
}

When I click on either the image button or the link button, the new page opens and the clicked page does a postback.

How can I avoid the postback and just open the new page.

I tried the following:

protected void Page_Load(object sender, EventArgs e)
{
    Lb4.Attributes.Add("OnClick", "javascript:return false;");
}

When I click the button, nothing happens.

You can do that in javascript or set OnClientClick property , explained here - https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.onclientclick(v=vs.110).aspx .

Or just use PostBackUrl property. There are lot of options or simple remove server control use html a-href only. for image button- use <img> and wrap with <a> .

If you don't want to postback, I would recommend just using HTML for your button then. http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_link_image

The other option is using the button's onclientclick method. If you don't define an OnClick it probably won't postback. (I think anyway) https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick%28v=vs.110%29.aspx

If you want to avoid the postback, you have to move that if-else logic to the client (JavaScript). As for the Master.Client.ID property, one approach is to expose the value in the markup, for example in a <input type="hidden"> that you can then use in the JavaScript.

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