How to add image in div.Innerhtml asp c#?

12,326

Solution 1

Add "img" tag into Desc. Then set it in div's innerhtml.

Desc=Desc+ "<img src=" + ImgUrl + " />";
divContent.InnerHtml = Desc;

else

Image img = new Image();
img.ImageUrl = ImgUrl;
divContent.Append(img);
divContent.Append(Desc);

Solution 2

Use this to show image in Div

div.Style("background-image") = Page.ResolveUrl("~/Images/xyz.JPG")

Solution 3

You can add it like this.

Desc +=  "<img id=\"img1\" src="+ ImgUrl + " />";
divContent.InnerHtml = Desc;

Solution 4

When you set InnerHtml you overwrite all Controls you added (as you found out).

Solution: add another control, such as a LiteralControl where you put in the text.

Image ThumbImg = new Image();
ThumbImg.ImageUrl = ImgUrl; 

HtmlGenericControl divContent = new HtmlGenericControl("div");
divContent.Controls.Add(ThumbImg);
LiteralControl lit = new LiteralControl();
lit.Text = Desc;
divContent.Controls.Add(lit);

Or, as an alternative, use the Label control. Difference: Label uses escaping before showing your text, LiteralControl doesn't.

Share:
12,326
Morpheus
Author by

Morpheus

Bones: HTML; Skin: CSS; Muscle: JavaScript; Brains: PHP;

Updated on June 04, 2022

Comments

  • Morpheus
    Morpheus almost 2 years

    I want to add image to div, but innerHtml overrides it. How I need to achieve this? This is what I have for now:

    Image ThumbImg = new Image();
    ThumbImg.ImageUrl = ImgUrl; 
    
    HtmlGenericControl divContent = new HtmlGenericControl("div");
    divContent.Controls.Add(ThumbImg);
    divContent.InnerHtml = Desc;
    

    If I move divContent.Controls.Add(ThumbImg); line to the end, then it adds an image, but to the end of content and I want image to be in beginning of the content.