ASP:Net LinkButton control Postback issue

762 Views Asked by At

I have an asp.net linkButton (or imageButton) control in my profile.aspx page. I'am checking Request.Querystring("id") in the page below in the code behind.

http: //localhost:42932/profile.aspx?id=1

When I first load the profile page it is not posted back. It is ok!. When I go to another users profile (the same page just the query string is different) using imageButton control with the adddress;

http: //localhost:42932/profile.aspx?id=2

it is posted back. I dont want it to be posted back. But if I go to this page with a regular html input element like

a href = "http: //localhost:42932/profile.aspx?id=2"

it is not posted back. So I want the image button behave like an html input element.

Here is my imageButton;

ASPX:

<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server"/>

.CS

imgProfile.PostBackUrl = "profile.aspx?id=" + Session["userID"];

Edit:

 if (!IsPostBack)
    {
        Session["order"] = 0;
    }

This control is in the page load. So it should be !postback with state I mentioned above. Because all the other functions are working when Session["order"] = 0

2

There are 2 best solutions below

3
On

Make use of OnCLientClick instead of OnClick, so that you only run client side code. Then, sepcify that you return false;

i.e.

<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server" OnClientClick="return false;" />

But, why use a server control, when this can be done with a normal <img .. html control?

1
On

Rather than specifying a PostBackUrl I would recommend using Response.Redirect() in the button click event handler:

public void imgProfile_Click(object sender, eventArgs e){
   Response.Redirect("profile.aspx?id=" + Session["userID"]);
}

Or alternatively, just use a Hyperlink control and set the NavigateUrl property during Page_Load:

<asp:HyperLink ID="imgProfile" runat="server"><img src="images/site/profile1.png" /></asp:Hyperlink>

imgProfile.NavigateUrl = "profile.aspx?id=" + Session["userID"];