bob
bob

Reputation: 227

Asp.Net trouble with links

I am new to web dev in ASP.NET, I seem am running into trouble with links. Here are a couple of questions:

I have this in my masterpage file:

<div class="title">            
                <a href="~/Default.aspx">Backyard Cures</a>
            </div>

When a user clicks on the title, I want him/her sent back to the home page. However, this doesn't seem to be working. Instead, when I am in the Login or registration pages it sends me back to the login page. When I am in default.aspx it sends me to /localhost/~/Default.aspx. Doesn't the ~ mean root?

I am also wondering how to make my urls more user-friendly. I don't want Default.aspx appearing for the home page etc.

Upvotes: 0

Views: 64

Answers (2)

joym8
joym8

Reputation: 4202

The anchor tag (<a>) is a standard HTML tag and tilde character (~) is specific to .NET

You should use <asp:HyperLink runat="server" NavigateUrl="~/Default.aspx" Text="Backyard Cures"></asp:HyperLink> when utilizing the tilde character.

Also, if your Master Page or Content Page or a resource it uses is protected by authentication you will be redirected to login page.

For making links more readable you can use one or more options from below:

  1. Friendly Urls package from nuget: http://www.nuget.org/packages/Microsoft.Aspnet.FriendlyUrls/
  2. Switch to MVC project instead of Web Forms project
  3. Use custom routing: http://msdn.microsoft.com/en-us/library/vstudio/cc668201%28v=vs.100%29.aspx

Upvotes: 2

Tushar Gupta
Tushar Gupta

Reputation: 15913

Change to HyperLink to run as a Web Control:

<asp:HyperLink NavigateUrl="~/BusinessOrderInfo/page.aspx" Text="Whatever" runat="server" />

Or, run the anchor on the server side as an HTML Control:

<a href="~/BusinessOrderInfo/page.aspx" runat="server" >

Or, use Page.ResolveUrl:

<a href="<%= Page.ResolveUrl("~/BusinessOrderInfo/page.aspx") %>">...</a>

For making the url prettier

With web forms, the url is pointing to a file on your disk, with MVC is pointing to a controller action. If you're using webforms, you'd want to use URL rewriting. Scott Guthrie has a good article on doing URL rewriting.

Upvotes: 1

Related Questions