[英]How do I display an image in a web form in asp.net Visual Studio?
I have created an image folder in my root project folder我在我的根项目文件夹中创建了一个图像文件夹
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
I am linking my images here:我在这里链接我的图片:
if (dropDownList.SelectedItem.Value == "Picture 1")
{
Image1.ImageUrl = "~/images/picture1.jpg"
}
When I visit the web page I get a small img box with an x instead of my image.当我访问网页时,我得到一个带有 x 的小 img 框,而不是我的图像。
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
is setting the url to a directory (folder), not an image.正在将 url 设置为目录(文件夹),而不是图像。 That's why you're getting the small image-box and not an image.这就是为什么你得到小图像框而不是图像的原因。
If you want an image to show up when the page loads, set it to a valid image:如果您希望在页面加载时显示图像,请将其设置为有效图像:
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
This line of code is setting an invalid image url as it only contains the folder path.这行代码设置了一个无效的图像 url,因为它只包含文件夹路径。 So in your code you must ensure that you override the Image1's ImageUrl property to valid image file.因此,在您的代码中,您必须确保将 Image1 的 ImageUrl 属性覆盖为有效的图像文件。 Based on your requirement here is something you can do.根据您的要求,这里是您可以做的事情。
In aspx page, set the image url to picture1.jpg assuming that option1 is selected by default in the dropdown so picture1.jpg will be displayed on initial page load.在 aspx 页面中,假设在下拉列表中默认选择 option1,将图像 url 设置为 picture1.jpg,因此在初始页面加载时会显示 picture1.jpg。
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
Next, set the AutoPostBack property of your dropdown to true so that image source code can be updated dynamically based on dropdown selected value接下来,将下拉列表的 AutoPostBack 属性设置为 true,以便可以根据下拉选择的值动态更新图像源代码
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
In selectedIndexChanged event handler update image source based on the selectedItem在 selectedIndexChanged 事件处理程序中,根据 selectedItem 更新图像源
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Image1.ImageUrl = "~/images/" + DropDownList1.SelectedItem.Value;
}
Hope this helps希望这可以帮助
It was displaying the small image box with X as it was not able to find the image at the path specified.它显示带有 X 的小图像框,因为它无法在指定的路径中找到图像。
So, Add you images folder in wwwroot folder instead of Project root.因此,在wwwroot文件夹而不是项目根目录中添加您的图像文件夹。
After that you can use <asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
之后你可以使用<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
尝试使用 .Scr 而不是 ImageUrl。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.