Clients Which works great. B...">

ASP MVC href for controller / view

I have it:

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

Which works great. But if I'm already on this page or on the controller, for example. /Users/Details , and I click on this link, it redirects me to /Users/Index .

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

+72
href asp.net-mvc razor asp.net-mvc-4
Jul 16 '13 at 8:00
source share
7 answers

There are several ways you can do this. You can do the following:

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

or that:

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

Recently, I have been doing the following:

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

The result will have http://localhost/10000 (or with any port you use) to add to the URL structure, for example:

 http://localhost:10000/Users 

Hope this helps.

+146
Jul 16 '13 at 8:08
source share

What about

 <li> <a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a> </li> 
+14
Jul 16 '13 at 8:03
source share

You can change the following

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

An extra dot means that you are on the same controller. If you want to change the controller to another controller, you can write this

 <li><a href="../newController/Index" class="elements"><span>Clients</span></a></li> 
+5
Jun 05 '15 at 4:58
source share

Try the following:

 <a asp-controller="Users" asp-action="Index"></a> 

(Valid for ASP.NET 5 and MVC 6)

+4
Jun 02 '15 at 1:47
source share

Here '~' refers to the root directory where Home is the controller and Download_Excel_File is the actionmethod

  <a href="~/Home/Download_Excel_File" /> 
+3
Jul 17 '17 at 7:19
source share

You can also use this very simplified form:

 @Html.ActionLink("Come back to Home", "Index", "Home") 

Where:
Come back to Home is the text that appears on the page.
Index is the name of the view.
Home - controller name

+1
Nov 09 '17 at 2:14 on
source share

If you are using ASP.NET Core, you can configure the accepted answer as follows:

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

replacing @Request.Url.Scheme with @Context.Request.Scheme

0
Jan 23 '19 at 17:31
source share



All Articles