Mike
Mike

Reputation: 257

How to get img src that changed by JavaScript in code behind C#.NET

this is my client code:

<form id="form1" runat="server">
    <div>
        <img id="mm" runat="server" />
    </div>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <script>
        document.onclick = function () {
            mm.src = "photo1.jpg";
        }

    </script>
</form>

and I try to get img src in code behind, but it returns null :

protected void Button1_Click(object sender, EventArgs e)
{
    string s1= Request.Form["mm"];
    string s2= mm.Attributes["src"];
    string s3 = mm.Src;
}

How can I do this?

Upvotes: 1

Views: 3112

Answers (1)

Aristos
Aristos

Reputation: 66641

You simple can not. You can not get on code behind the srcof an image after have been change by javascript.

This is because this information is not travel back to server even by post back.

The work around is to save at the same time with the src to a hidden input control on the value... the same data.

So after the post back you read the value from that input control, because only that type of controls send back their values.

Here is an example base on your code

<asp:HiddenField runat="server" ID="ImgExSrc" />

<script>
    document.onclick = function () {
       mm.src = "photo1.jpg";
       document.getElementById("<%=ImgExSrc.ClientID%>").value = mm.src;
    }
</script>

and on code behind you just read the ImgExSrc.Value after the post back. Only with post back you can send your values to the server side.

Upvotes: 4

Related Questions