Search code examples
c#asp.netcode-behind

write the same code from aspx page to behind code in the cs page


is there a way to write this code from an aspx page to a behind code of the aspx page (cs), in asp.net.

<a rel="lightbox" id="userImageLightBox" runat="server" title="profile image">
    <img id="userImage"  runat="server"  width="150"  height="146"  alt="" src=""/>
</a>  

for example if i have the code in apsx:

<asp:Label ID="pageProfileHeadName" runat="server" Visible="true"/>

in the behind code i can do:

    Label label = new Label();
    label.ID = "pageProfileHeadName";
    label.Visible = true;

thanks


Solution

  • Since you have already set the runat="server" attribute, you can access the HTML controls in your code-behind through its id:

    // *.aspx:
    <a id="userImageLightBox" runat="server" ...>
        <img id="userImage" runat="server" ... />
    </a> 
    
    // code-behind:
    userImageLightBox.Title = "New Title";
    userImage.Src = "~/images/profile.png";
    
    // To get or set an attribute like `rel`:
    userImageLightBox.Attributes["rel"] = "test";
    

    Update: If you want to create the HTML from the code-behind, you can do as JonH wrote:

    HyperLink a = new HyperLink();
      a.ID = "userImageLightBox";
      a.Attributes["rel"] = "lightbox";
    
      Image img = new Image();
      img.ID = "userImage";
      img.ImageUrl = "img.png";
      img.Width = 150;
      img.Height = 146;
    
      a.Controls.Add(img);
    

    Oh, and please increase your accept rate.