input losing src

If I use the following code without runat=”server” the input’s src works fine and I see the image coming through.

<div><input id="testButton" type="image" src="<%=TestButtonImageUrl %>" onserverclick="RedirectTest" /></div>

url is https://fpdbs.paypal.com/dynamicimageweb?cmd=_dynamic-image

But if I put the runat=”server” in, for some reason, I get this for the url:

<div><input id="testButton" type="image" src="<%=TestButtonImageUrl %>" onserverclick="RedirectTest" runat="server" /></div>

url is http://localhost/%3C%=lButtonImageUrl%20%%3E

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You cannot use the <%= %> syntax with server controls (including standard HTML elements with runat="server"). You have two choices:

  • Access the control in the code behind (as an HtmlInputControl) and assign the src attribute using the Attributes property: imageControl.Attributes["src"] = value;
  • Assign the attribute using the databinding syntax (src="<%# %>") and call imageControl.DataBind() from the code behind

Solution 2

Maybe I’m missing something. But runat server tag does not support code expression.

Solution 3

When you add runat=”server to that html tag, Asp.Net converts it from string to HtmlControl – in this case of type HtmlInputImage. You can see this happen by adding:

<%= testButton.GetType() %>

Then the only thing you need to do is set the Src-property, which, contrary to other comments, you CAN do in inline aspx – no need for a code-behind file:

<%
    testButton.Src = "/content/logo.png";
%>
<input id="testButton" type="image" runat="server" src="" onserverclick="RedirectTest" />

You need to set the Src-property BEFORE the actual input, which is a bit non-intuitive, the reason is that the code is run at render-time, so if the setting of Src-property is after the control, it is too late.

Solution 4

if jQuery is an option than you could try this:

<script type="text/javascript">
  $(function() { $('#<%=testButton.ClientID %>').attr('src', '<%=TestButtonImageUrl %>'); });
</script>
...
<div><input id="testButton" runat="server" type="image" onserverclick="RedirectTest" /></div>

Update:
Another option is to create a HttpHandler with processing like this

public void ProcessRequest(HttpContext context)
{
  var testButtonImageUrl = "https://fpdbs.paypal.com/dynamicimageweb?cmd=_dynamic-image";
  context.Response.Redirect(testButtonImageUrl);
}

add in web.config path to handle image.img or whatever and update aspx

<div><input id="testButton" runat="server" type="image" src="image.img" onserverclick="RedirectTest" /></div>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply