Cyril Gupta
Cyril Gupta

Reputation: 13723

Is Adding runat="server" to HTML tags to get relative path in ASP.net an elegant solution?

I've got a couple of ASP.Net Usercontrols that I am using in different locations of my new website. These usercontrols had links like this :

<a href="daily/panchang/"></a>

If the usercontrol is used in pages in various subdirectories the relative path just doesn't work, and I don't want to provide my full website name in the path. So I did this

<a href="~/daily/panchang/" runat="server">

and now the ASP.Net '~' marker works correctly to resolve the root path.

Is it okay to mark all my HTML tags where I have the need to resolve the root path with runat="server" or do you know of a better, HTML way?

Thanks

Upvotes: 6

Views: 2630

Answers (3)

Cristian Libardo
Cristian Libardo

Reputation: 9258

I won't say whether it's an elegant solution, I'll just point out an alterantive within System.Web:

<a href="<%= VirtualPathUtility.ToAbsolute("~/daily/panchang/") %>">

Upvotes: 7

Diadistis
Diadistis

Reputation: 12174

You should use a base tag to define the root of your application and make all links relative like this :

<head>
    <base href="<%= Request.ApplicationPath %>" />
</head>
...
<a href="daily/panchang/"></a> <!-- this now points to ~/daily/panchang/ -->

Upvotes: 5

Andreas Grech
Andreas Grech

Reputation: 108060

Be careful though because every element that has runat="server" will be 'serialized' and stored in the ViewState every time a PostBack occurs, and you don't wanna be cluttering it up with useless data.

Upvotes: 4

Related Questions