Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

c# - How to use asp:image in code behind

I have a problem with rendering asp:image in code behind. First I explain my method: In Default.aspx I just use one label. In code behind I make a string variable and fill it, then I fill the lable.Text by my string variable.
this is my Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="test_Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
   <div>
      <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   </div>
</form>
</body>
</html>

and this is my form load function in Defaul.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    Label1.Text = @"<asp:Image ID='Image1' runat='server'   ImageUrl='~/images/sc/tiraje.jpg' />
                    <br/>
                    <img src='../images/sc/tiraje.jpg' />
                    ";
}

Now this code must render two images. But first image used by asp:image doesn't work! I need to use asp:image in my string variable because my URL changes my result, for example if my URL is:

http://localhost:19551/website/test/Default.aspx

When I give it one "/":

http://localhost:19551/website/test/Default.aspx/ 

The second URL causes to change the src of second image in my string that I use in <img> tag. so that I want to use asp:image because it uses "~/" for src (imageUrl) that never changes by change URL!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Literal control introduced by Abdullah ELEN is the easiest and it works. Like this:

       <asp:Literal ID="Literal1" runat="server"></asp:Literal>

And then in the code behind, assuming you have already captured the image source into a local variable (photo_src), you add this:

        Literal1.Text += "<img src=" + '"' + photo_src + '"' + "/>";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...