views:

146

answers:

2

I'm sure I've done this before, but can't remember the syntax. How do I include a session variable in nagivateUrl in a hyperlink?

I've tried this:

<asp:HyperLink ID="lnkMyLink" runat="server" Text="My Link" 
 NavigateUrl='<%# "http://absoluteURL.org?param=" +
 Session["myParameterValue"].ToString()%>'></asp:HyperLink>

and this:

<asp:HyperLink ID="lnkMyLink" runat="server" Text="My Link" 
 NavigateUrl='<%# String.Format("http://absoluteURL.org?param={0}",
 Session["myParameterValue"].ToString()) %>'></asp:HyperLink>
+1  A: 

If your link is not in a data-bound control, such as a ListView, you can still force databinding (per your first code snippet) by calling .DataBind() on the control from code-behind.

kbrimington
Thanks, kbrimington, I forgot to check that:) I'll mark it as the answer after 10 minutes, as it won't let me mark it immediately.
HappyCoder4U
+1  A: 

Because you've used the data binding format (<%#), you need to call the HyperLinks .DataBind() method from your codebehind.

You need your Page_Load method to look something like this:

protected void Page_Load(object sender, EventArgs e)
{
    lnkMyLink.DataBind();
}

The only thing to bear in mind that using Data Binding for something like this, i.e. not specifically Data Binding, may be a bit confusing for anyone who has to maintain your code in the future. Whilst it'll be fairly quick and easy to determine what you've done and why you've done it, anything that can cause future confusion should be removed from your code where posible. Therefore a potentially better option would be to put the following in your Page_Load:

lnkMyLink.NavigateUrl = 
    string.Format("http://absoluteURL.org?param={0}", Session["myParameterValue"]);
Rob
Thanks, Rob. This is a better solution.
HappyCoder4U