Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 604
Zapnologica Avatar asked Jul 16 '13 08:07

Zapnologica


People also ask

How can create href link in ASP.NET MVC?

The Anchor Tag Helper generates HTML anchor (<a> </a>) element by adding a new attribute. The "href" attribute of the anchor tag is created by using new attributes. The Anchor Tag Helper generates an HTML anchor (<a> </a>) element by adding new attribute.

How does a controller find a view in MVC?

MVC by default will find a View that matches the name of the Controller Action itself (it actually searches both the Views and Shared folders to find a cooresponding View that matches). Additionally, Index is always the "default" Controller Action (and View).


1 Answers

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 

I hope this helps.

like image 137
Brendan Vogt Avatar answered Oct 03 '22 09:10

Brendan Vogt