如何在代码后面使用asp:图像
本文关键字:asp 图像 代码 | 更新日期: 2023-09-27 18:08:36
我有一个渲染asp:图像在代码后面的问题。首先我解释一下我的方法:在Default.aspx
中,我只用一个标签。在后面的代码中,我创建一个字符串变量并填充它,然后我用字符串变量填充lable.Text
。
这是我的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>
这是我在default。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' />
";
}
现在这段代码必须呈现两个图像。但是asp:image使用的第一个图像不工作!我需要在我的字符串变量中使用asp:image因为我的URL改变了我的结果,例如,如果我的URL是:
http://localhost:19551/website/test/Default.aspx
当我给它一个"/":
http://localhost:19551/website/test/Default.aspx/
第二个URL导致改变我在<img>
标记中使用的字符串中的第二个图像的src。所以我想使用asp:image,因为它使用"~/"为src (imageUrl),永远不会改变更改URL!
由Abdullah ELEN引入的Literal控件是最简单的并且它有效。这样的:
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
然后在后面的代码中,假设您已经将图像源捕获到一个局部变量(photo_src)中,您添加以下内容:
Literal1.Text += "<img src=" + '"' + photo_src + '"' + "/>";
您不能以这种方式创建,因为Asp:Image
是服务器对象。我为你准备了一个简单的例子。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="pageDefault" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="literalControl" runat="server" />
</div>
</form>
</body>
</html>
后台代码
protected void Page_Load(object sender, EventArgs e)
{
// Write here your SQL query for image URLs..
while(reader.Read())
{
literalControl.Text +=
"<img src='"../images/sc/" + reader[0].ToString() + ".jpg'" /><br/>";
}
}
你不应该使用标签来呈现图像。相反,在web表单中放置两个asp:image控件或使用占位符控件,例如:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Application.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image runat="server" ID="Image1" />
<br />
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
然后你可以动态地创建一个新的图像控件,并通过使用它们的ImageUrl属性设置图像url:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Image1.ImageUrl = "../images/sc/tiraje.jpg";
Image Image2 = new Image();
Image2.ImageUrl = "../images/sc/tiraje.jpg";
PlaceHolder1.Controls.Add(Image2);
}
}