Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using server variables in a href <%= xx %> with runat=server

Tags:

c#

asp.net

When I use an anchor tag on an aspx page as below,

<a href="~/pages/page.aspx?id=<%= ServervariableName %>"> test </a>

it will get the variable value correctly assigned to id but it won't route the page correctly as the ~ will not be evaluated without the runat="server" attribute on the 'a' tag. But once I add the runat server attribute, it does not evaluate the servervariable name anymore.. Does anyone know how this works or what I should do to take care of both?

like image 304
user479843 Avatar asked Nov 29 '10 18:11

user479843


3 Answers

Try the following:

href="<%= ResolveUrl("~/pages/page.aspx") + "?id=" + ServervariableName %>"

This will only work if you do not add runat="server".

like image 126
Pieter van Ginkel Avatar answered Nov 09 '22 05:11

Pieter van Ginkel


You cannot use this syntax to set properties of server-side controls.

Instead, you can set the property in the code-behind, or use data-binding syntax (<%# expression %>) and call DataBind() in the code-behind.

like image 45
SLaks Avatar answered Nov 09 '22 03:11

SLaks


If you want both runat=server and a virtual path you either of:

  1. Set the href in your code behind. Afaik MapPath doesn't remove query strings.
  2. If you don't want to use MapPath, you can use VirtualPathUtility which MapPath uses internally most likely.
  3. If you want to bind the variable in your .aspx-file and still want runat="server", then you have to use an expression builder. You syntax then becomes

    <a href="~/folder/page.aspx?id=<%$ MyVars:ServerVariableName %>" runat="server">The link</a>

PM me if you need help with it. It's quite useful for customizing localization and for interfacing the ASP.Net compiler (i.e. not the C#/VB one, but the one that can compile ASPX-pages)

like image 31
Henrik Avatar answered Nov 09 '22 05:11

Henrik