简体   繁体   中英

Why clicking an ImageButton in an Aspx page works only at second time?

My goal is to display an image inside an ImageButton, after clicking on it. This works only when I click the Button second time. My markup:

   <%@ Page Title="" Language="C#" MasterPageFile="Site.Master" AutoEventWireup="true" 
              CodeBehind="Images.aspx.cs" Inherits="Monitas.Images" %>
     <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
     <style media="all">

       .Sheet {position: relative; left: 15%; top:15%; background: white; width: 800px; 
             height: 900px; border:3px solid #000;}

       .HeaderLogo {position: relative; background: yellow; width:240px; height:100px; left: 
             500px; top: 1px;  border:1px solid #000;}

        </style>

        </asp:Content>
        <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

        <asp:Panel ID="FOGLIO" class="Sheet" runat="server">

            <asp:ImageButton class="HeaderLogo" ID="HEADERLOGO" alternateText="Header Logo" 
                    runat="server" ImageAlign="Middle" OnClick="OnImageHeaderClick" />

       </asp:Panel>

   </asp:Content>

And code behind: (OnImageHeaderClick seem to send a PostBack, but doesn't assign HeadImage Only at second time I click, it assigns the variable)

   protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack) // Only second PostBack displays the HeadImage assigned by 
                OnImageHeaderClick
        {
            HEADERLOGO.ImageUrl = HeadImage; // HeadImage is static Global
            Response.Write(HEADERLOGO.ImageUrl);
        }

    }
     // This seems not to be triggered a first time, despite it is declared in the Markup
    protected void OnImageHeaderClick(object sender, ImageClickEventArgs e)
    {
        HeadImage = "Images/FooterLogo.png"; // assign image
    }

I discovered the way to avoid the second click. Actually it is enough to assign the HeaderLogo.ImageUrl during the OnImageHeaderClick, as shown in following code snippet:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            HEADERLOGO.ImageUrl = HeadImage;
        }

    }
    protected void OnImageHeaderClick(object sender, ImageClickEventArgs e)
    {
        HEADERLOGO.ImageUrl = HeadImage = "Images/FooterLogo.png"; // use another image for experiment
    }

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