Asp.net mvc 4 method call from controller by button

In my controllers, I have an AccountController class and inside this method there is

[HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { WebSecurity.Logout(); return RedirectToAction("Index", "Home"); } 

In my views I have a cshtml page with the body and this piece of code

 <form class="float_left" action="Controllers/AccountController" method="post"> <button class="btn btn-inverse" title="Log out" type="submit">Log Off</button> </form> 

And this does not work, does anyone know what is the problem or some other simple solution?

+6
source share
3 answers

You do not reference the action method here:

 action="Controllers/AccountController" 

First you don’t need to specify Controllers/ , because the infrastructure will find a controller for you. In fact, the concept of a “folder” of controllers is unknown to the client / URL / etc. What you need to give is a “route” to a specific action method.

Since the MVC structure knows where the controllers are located, you only need to specify which controller and which method of action on this controller:

 action="Account/LogOff" 
+4
source

The action attribute indicates an incorrect controller action. Your controller action is called LogOff , not AccountController . You should never manually create <form> elements like this, but always use html helpers that are designed for this purpose:

 @using (Html.BeginForm("LogOff", "Account")) { <button class="btn btn-inverse" title="Log out" type="submit">Log Off</button> } 
+5
source

The form action must be /Account/LogOff

 < form class="float_left" action="/Account/Logoff" method="post"> <button class="btn btn-inverse" title="Log out" type="submit">Log Off</button> </form> 

Try putting this in a .cshtml file:

 @using (Html.BeginForm("LogOff", "Account")) { <button class="btn btn-inverse" title="Log out" type="submit">Log Off</button> } 
0
source

All Articles