Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke an MVC action method from a href in an anchor?

I'm using the markup as follows.

@Html.ActionLink(@User.Identity.Name, "LogOut", "Account")

Now, I need to add a span inside the anchor because I want to use glyphs from Bootstrap. As far my googlearch went, there's no way to specify it using the helper above. So, I've redesigned it to explicit HTML as follows.

<a href="~/Account/LogOut">
  <span class="glyphicon glyphicon-log-out"></span>
  <span>@Global.LogOut @User.Identity.Name</span>
</a>

It works but the link isn't always targeting the same address as the first example does. It's because I've got en/ or se/ etc. for language first. When routing based on MVC, the language prefix stays in place but it gets lost when specifying the URL explicitly.

How can I specify a call to the specific action method?

like image 421
Konrad Viltersten Avatar asked Apr 30 '16 22:04

Konrad Viltersten


People also ask

Can we use action in anchor tag?

asp-actionIt is used to specify the name of the action method (in the Controller) that helps us to generate the URL. The generated URL is placed in the href attribute of the anchore tag.

How is action method linked to the view?

The following illustrates the Index() action method in the StudentController class. As you can see in the above figure, the Index() method is public, and it returns the ActionResult using the View() method. The View() method is defined in the Controller base class, which returns the appropriate ActionResult .

Which action is invoked when we call any controller in MVC?

Index() action is invoked, a view is not returned. Instead, the raw text "Hello World!" is returned to the browser. If a controller action returns a result that is not an action result - for example, a date or an integer - then the result is wrapped in a ContentResult automatically.


1 Answers

Try:

<a href="@Url.Action("LogOut", "Account")">
  <span class="glyphicon glyphicon-log-out"></span>
  <span>@Global.LogOut @User.Identity.Name</span>
</a>
like image 184
fordareh Avatar answered Oct 20 '22 21:10

fordareh