asp.net-mvc asp.net mvc 4 通过按钮从控制器调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16064481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:44:43  来源:igfitidea点击:

asp.net mvc 4 calling method from controller by button

asp.net-mvcbuttonasp.net-mvc-4controllers

提问by mikrimouse

In my Controllers i have class AccountController and within in i have this method

在我的控制器中我有类 AccountController 并且在我有这个方法

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

In my Views i have cshtml page with body and this part of code

在我的视图中,我有带有正文和这部分代码的 cshtml 页面

<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 doesn't work, anyone know what is problem or some other simple solution?

这不起作用,有人知道什么是问题或其他一些简单的解决方案吗?

采纳答案by David

You're not referencing the action method here:

您没有在此处引用操作方法:

action="Controllers/AccountController"

For starters, you don't need to specify Controllers/because the framework will find the controller for you. Indeed, the notion of a "folder" of controllers isn't known to the client/URL/etc. What you need to give it is a "route" to the specific action method.

对于初学者,您不需要指定,Controllers/因为框架会为您找到控制器。实际上,客户端/URL/等不知道控制器“文件夹”的概念。您需要给它的是特定操作方法的“路线”。

Since the MVC framework knows where the controllers are, you need only tell it which controller and which action method on that controller:

由于 MVC 框架知道控制器在哪里,您只需要告诉它哪个控制器以及该控制器上的哪个操作方法:

action="Account/LogOff"

回答by Darin Dimitrov

The actionattribute is pointing to a wrong controller action. Your controller action is called LogOffand not AccountController. You should never be manually building <form>elements like that but always use the html helpers that are designed for this purpose:

action属性指向错误的控制器操作。您的控制器操作被调用LogOff而不是AccountController。您永远不应该像这样手动构建<form>元素,而应始终使用专为此目的设计的 html 帮助程序:

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

回答by Rohrbs

The form action should probably be /Account/LogOff

表单操作可能应该是 /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 the .cshtmlfile:

尝试将其放入.cshtml文件中:

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