helloWorld helloWorld -3 years ago 74
C# Question

How can I pass in a query string variable to a link that has runat="server" tag on it

<a id="link1" href="home.aspx?theYear=<%=(selectYear)%>"></a>


vs.

<a runat="server" id="link2" href="home.aspx?theYear=<%=(selectYear)%>"></a>


In my code behind I have
public string selectYear="2017";
defined.

The first link I have works as expected. It will have the actual value of the selectYear as the query string variable.
But the second one (the one with
runat="server"
) doesn't do that.

How can I have the
runat="server"
and still be able to make it behave like the first link?

Answer Source

<%= %> is a shortcut for Response.Write so it won't work inside your user control.

So can implement that using DataBinding markup <%# %>, but you have to be sure that someone will call the DataBind method- You could call the DataBind manually, link2.DataBind(), or call the page DataBind in case you have many links like that.

<a runat="server" id="link2" href="home.aspx?theYear=<%# selectYear%>"></a>

Another way to implement that is by just simple set the NavigateUrl from the server side:

link2.NavigateUrl = $"home.aspx?theYear={selectYear}";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download