Reputation: 61
I am trying to find a way to execute a method in my layout view only when a link is clicked. Here's my code so far:
The method I want to call (also in the view):
@functions{
public void Logout()
{
Session.Abandon();
Response.RedirectToRoute(new { controller = "Home", action = "Index"});
}
}
The link that'll be clicked to call that method:
<a onclick="// Call the method from here" href="#">Log Out</a>
The question is, how do I go about this?
Upvotes: 0
Views: 5047
Reputation: 131
You can also achieve this by href
<a href="@Url.Action("ActionName","ControllerName")">Log Out</a>
Upvotes: 0
Reputation: 62498
You can add a controller action in your account controller and then invoke it.
For example, one quick way is to add action method:
public class AccountController : Controller
{
public ActionResult Logout()
{
Session.Abandon();
return RedirectToAction("Index","Home");
}
}
and in view you can do it via js:
<a onclick="location.href='@Url.Action("Logout","Account")'" href="#">Log Out</a>
A better way is to create action as HttpPost
and do it via a form post. but the above example gives an idea how you can do that on the link click on client side.
Upvotes: 2