简体   繁体   中英

How to pass a variable to src attribute in HTML img tag

the image in my .aspx file

 <img src='<%=vPath%>' alt="" id="image" />

in aspx.cs

 public string vPath  ;
 protected void BtnSearchFarms_Click(object sender, EventArgs e)
    {string vImageName = LblFarmId.Text;

string vPath = "~/attachments/survey/" + vImageName + ".jpg";}

how can I pass the vPath variable to src in the img tag? is it correct? it still doesn't show any result in the img tag when I execute the page

Not sure exactly what you are trying to achieve or whether you are going about it correctly, but the very simplest, quick and easy way to do this is:

<asp:Button id="BtnSearchFarms" OnClientClick="imageToHiddenField()" />
<input type="hidden" name="imgHidden" id="imgHidden" />

Then javascript:

function imageToHiddenField() {
    document.getElementById("imgHidden").value = document.getElementById("image").src;
}

The value will be added to the hidden field and will go back with the posted data. It can be retrieved using Request.QueryString["imgHidden"] or Request.Form["imgHidden"] depending on whether you are using POST or GET.

Not elegant, but it should work.

It's hard to tell from your question but it sounds like you have an image on your page and you're trying to change the src based on user input?

I'd say instead of using <img> the easiest way is to use an <asp:Image> which then has an ImageUrl property you can set. An ASP Image works generally like a regular img except you can use ~ in your paths.

protected void BtnSearchFarms_Click(object sender, EventArgs e)
{
    string vImageName = LblFarmId.Text;
    theAspImage.ImageUrl = "~/attachments/survey/" + vImageName + ".jpg";
    theAspImage.Visible = true;
}

And in the aspx:

<asp:Image id="theAspImage" runat="server" Visible="false" />

If you can't use an asp:image then you need to resolve the path so it doesn't have a ~. You can use Page.ResolveUrl("~/attachments/survey/" + vImageName + ".jpg") which will convert it to a web accessible path.

One important note, very important note, you have string vPath inside your event handler. That means you're creating a new variable not modifying your public instance variable. Change:

string vPath = "~/attachments/survey/" + vImageName + ".jpg"; To: vPath = "~/attachments/survey/" + vImageName + ".jpg";

If neither of those answer your question, then I think we need more information.

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