简体   繁体   中英

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

Short answer - yes - a hyperlink control renders as <a> so you could do this:

Hyperlink a = new Hyperlink();
a.ID = "userImageLightBox";

See the MSDN regarding this server control:

http://msdn.microsoft.com/en-us/library/k0b15efk(v=vs.71).aspx

Anytime a control is runat=server this means you will be able to access it from the aspx code behind page (.cs, .vb, etc). So if you ever want to change a specific property, such as the NavigateURL property you could do so.

a.NavigateURL = "someURL";

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.

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