tags:

views:

32

answers:

2

Is there a way to do something like this:

<asp:HyperLink id="MyLink"
  NavigateUrl="../mypage.aspx?id=<%= pageid %>"
  runat="server">My Page</asp:HyperLink>

... except in a way that works?

I want to do this inline in a normal HyperLink control that is not databound.

Edit: Got some good answers, but what I'm looking for is how to do this specifically in a normal HyperLink (not in a DataGrid/GridView) and inline (not via a function call or code behind).

Updated my question to clarify.

+2  A: 

You can actually write a simple string method in your codebehind file.

Example

public string formatUrl(string pageId) {
    return "../mypage.aspx?id=" + pageId;
}

And then use it like..

<asp:HyperLink id="MyLink" NavigateUrl="<%= formatUrl(pageid) %>" runat="server">My Page</asp:HyperLink>

provided pageid exists

Marko
This is something I tried, but the code doesn't get run and it comes out as:http://localhost/MySite/<%= formatUrl(pageid) %>
metanaito
+2  A: 

You could do this in the codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string pageid = "123";
        MyLink.NavigateUrl = string.Format("../mypage.aspx?id={0}", pageid);
    }
}

UPDATE:

Now that @Marko Ivanovski pointed me in the comments that this hyperlink is inside a GridView which I didn't notice in the beginning the easiest would be to use databinding (<%# syntax):

<asp:TemplateColumn>
    <ItemTemplate>
        <asp:HyperLink 
            id="MyLink" 
            NavigateUrl='<%# Eval("pageid", "~/mypage.aspx?id={0}")  %>'
            runat="server">
        My Page
        </asp:HyperLink>
    </ItemTemplate>
</asp:TemplateColumn>

In this case pageid is a property of the data source.


UPDATE 2:

Do you really need a server side control? How about:

<a href="<%= this.ResolveUrl("~/mypage.aspx?id=" + pageid) %>">
    My Page
</a>
Darin Dimitrov
He mentions that the link is inside a GridView :)
Marko
@Marko, right, thanks for pointing this out. I didn't read the question carefully :-)
Darin Dimitrov
No probs - +1 for a good solution
Marko
Thanks for the solutions. I actually did want to find out how to do it outside a DataGrid/GridView. I'm using just a normal hyperlink. I updated the question to clarify. Also I'm looking for how to do it inline as opposed to using the .NavigateUrl property from codebehind.
metanaito
@metanito, this can't be done in the circumstances you describe. I would recommend you codebehind or simple HTML (I know that WebForms could have side effects to people using them too much - you simply forget the basics of how the web works).
Darin Dimitrov
Thanks. Yes, I thought about using just a normal <a> tag but I also want to set other properties of the link in code behind. Also, yes, using webforms for 10 years I've forgotten html :(
metanaito