Search code examples
asp.netasp.net-mvcasp.net-mvc-4razorhref

ASP MVC href to a controller/view


I have this:

<li><a href="/Users/Index)" class="elements"><span>Clients</span></a></li>

Which works fine. But if I am already on this page or on the controller e.g. /Users/Details and I click on this link it redirects me to /Users/Index.

How can I get the correct path in the href regardless of my current position on the site?


Solution

  • There are a couple of ways that you can accomplish this. You can do the following:

    <li>
         @Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
    </li>
    

    or this:

    <li>
         <a href="@Url.Action("Index", "Users")" class="elements">
              <span>Clients</span>
         </a>
    </li>
    

    Lately I do the following:

    <a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
         <span>Clients</span>
    </a>
    

    The result would have http://localhost/10000 (or with whatever port you are using) to be appended to the URL structure like:

    http://localhost:10000/Users