简体   繁体   中英

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.

<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />

is setting the url to a directory (folder), not an image. 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. So in your code you must ensure that you override the Image1's ImageUrl property to valid image file. 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.

<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

 <asp:DropDownList 
             ID="DropDownList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>

In selectedIndexChanged event handler update image source based on the 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.

So, Add you images folder in wwwroot folder instead of Project root.

After that you can use <asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />

for rest you can follow Mohsin's answer

尝试使用 .Scr 而不是 ImageUrl。

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