Use javascript to set image URL of image control in asp.net

29,397

Solution 1

First of all, understand that JavaScript doesn't understand, care, or even know about C# and its fancy "controls". It just deals with HTML. Period. That said, you can use JavaScript's setAttribute function to set the image URL of an img tag (not control). Like this:

document.getElementById('my-image').setAttribute('src', 'http://ecx.images-amazon.com/images/I/41%2BjAZ4dUGL._SS500_.jpg');

Demo here: http://jsfiddle.net/je9Gx/

Solution 2

You can use this code to find the image control, where imgid is ID of image control;

$("[id$='imgid']").attr("src",pathfromfileuploader);

//pathfromfileuploader=it is a variable which stores the path taken from file uploader;

Hope it will help :)

Share:
29,397
Ishan
Author by

Ishan

Hello i am into ASP.net C#/ Sharepoint development and constantly learning in order to expertise in the field.

Updated on August 11, 2020

Comments

  • Ishan
    Ishan over 3 years

    I have a Image, FileUpload and a Button controls. I want to save the image to the server from the local path obtained from FileUpload control. I implemented this functionality on Button Click in C#..

    Now i want to set the image URL of Image control OnClientClick of the same button on which server side code is implemented.

    Image URL will defer everytime depending on file selected in FileUpload control. Can anyone help me to understand how javascript can be used to set image URL based on thre file selected in File Upload Control?

  • Ayman Safadi
    Ayman Safadi over 11 years
    You're assuming the OP is using jQuery.
  • Pranav
    Pranav over 11 years
    asp control's id changes when rendered so you cannot find then directly. that's why Jquery is easier approach to find them.
  • Pranav
    Pranav over 11 years
    @AymanSafadi: yes..it is easier approach to find asp controls and much faster.
  • Ayman Safadi
    Ayman Safadi over 11 years
    @Pranav, I'm not disagreeing that using jQuery is easier... that's why it exists in the first place, I'm just saying that you shouldn't make the assumption that the OP is using, or even wants to use, jQuery. If getElementById won't work, the OP can find another selector that will work. The essence of my answer, and the answer to his question, is the use of setAttribute (which I just noticed you implemented in your answer). What he uses the function on, that's up to the OP. But yes, using jQuery would make it easier.
  • Pranav
    Pranav over 11 years
    OP is asking about ASP image control not HTML image that is why i suggested to use jquery , because it is very difficult to find asp control through plain javascript; you have to write Regex to find the control in javascript else one can use simple Jquery .