简体   繁体   中英

html from code behind

我想从(asp.net c#)后面的代码中插入带有几个控件+ style的html怎么办?

You could use a <asp:PlaceHolder> then add controls to this.

eg

Image img = new Image();
img.ImageUrl = "/someurl.jpg";
img.CssClass = "someclass";
img.ID = "someid";
img.AlternateText = "alttext"

PlageHolderId.Controls.Add(img);

This would produce the html

<img src="/someurl.jpg" class="someclass" id="someid" alt="alttext" />

You can then do this will any control, literal, hyperlink, button, table, etc...

You can add <asp:Literal> controls in the markup, then set their Text s in code-behind.
Make sure to set Mode="PassThrough" to prevent them from escaping the HTML.

You can add server-side controls by adding them to the Controls collection of any existing control (such as an <asp:Panel> )

Instead of Literal control you can use either HtmlGenericControl

HtmlGenericControl div = new HtmlGenericControl();
div.ID = "div";
div.TagName = "div";
div.Attributes["class"] = "container";
form1.Controls.Add(div);

Add a few <asp:PlaceHolder> 's to your template file in the <head> and <body>

Then use PlaceHolder1.Controls.Add();

I put a <asp:Panel ID="myPanel" runat="server"/> , and in the codebehind i add controls with:

myPanel.Controls.Add(...)

If you want to insert HTML code direct to the panel, use

myPanel.Controls.Add(new LiteralControl("Your HTML goes here!"))

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