Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner image and text of asp:LinkButton disappears after postback

I have a link button:

<asp:LinkButton ID="LinkButtonPrint" runat="server" OnClick="OnPrint_Click">
     <img src="img/print-icon.png" alt="" />
     <asp:Literal runat="server" Text="<%$ Resources:PrintPage %>" />
</asp:LinkButton>

In code behind I add an onclick handler in Page_Load like this:

LinkButtonPrint.Attributes["onclick"] = "StartLoadTracking(this, '" + GetLocalResourceObject("Loading") + "')";

The rendered HTML is like this:

<a href="javascript:__doPostBack('ctl00$LinkButtonPrint','')" 
id="ctl00_LinkButtonPrint" onclick="StartLoadTracking(this, 'Loading...');">
    <img alt="" src="img/print-icon.png">Print page
</a>

If I click this button it is working OK (it will respond with a PFD file so no HTML is sent back to the browser), but if I click another button on the page (which makes a full postback) the LinkButtonPrint will not have the inner content, it will be rendered like this:

<a href="javascript:__doPostBack('ctl00$LinkButtonPrint','')"  
id="ctl00_LinkButtonPrint" onclick="StartLoadTracking(this, 'Loading...');"></a>

If I remove the LinkButtonPrint.Attributes["onclick"] = ... line from Page_Load everything works fine (except my js function is not called, but that is normal).

What am I missing here?

EDIT
This is duplicate of
asp.net Link button image not visible after postback
but that one is not solved either :(

like image 882
ctekse Avatar asked Apr 04 '11 13:04

ctekse


2 Answers

This problem is now known to Microsoft, and they have published an official statement and workaround on the Microsoft Connect issue 718810: LinkButton controls collection lost on postback.

Microsoft statement is:

Thank you for the feedback. This seems like an oddity with the fact that the LinkButton control allows either direct text content via the Text property or in markup, or sub-controls via the Controls collection or markup. The workaround is to use a placeholder as the root content for the control and place the desired mixed content in there, e.g.

<asp:LinkButton runat="server">
    <asp:PlaceHolder runat="server">
        This is some text.</br>
        <asp:Label runat="server">This is a control</asp:Label>
    </asp:PlaceHolder>
</asp:LinkButton> 
like image 150
Fulvio Avatar answered Oct 04 '22 11:10

Fulvio


I found the solution:
I had to add runat="server" to the <img> tag inside the <asp:LinkButton>:

<img src="img/print-icon.png" alt="" runat="server" />
like image 35
ctekse Avatar answered Oct 04 '22 11:10

ctekse