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?
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.
What about
<li> <a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a> </li> 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> Try the following:
<a asp-controller="Users" asp-action="Index"></a> (Valid for ASP.NET 5 and MVC 6)
Here '~' refers to the root directory where Home is the controller and Download_Excel_File is the actionmethod
<a href="~/Home/Download_Excel_File" /> 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
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