【问题标题】:How to call a method from controller when a button from form is pressed?按下表单中的按钮时如何从控制器调用方法?
【发布时间】:2018-05-12 19:00:06
【问题描述】:

主要问题是当我按下按钮时,控制器中的方法没有被调用。 我在 MyController 的索引视图中有这个:

@using (Html.BeginForm())
{
@* .... *@
<form action="DoSomethingAction" method="post">
    <input type="text" id="IdString" name="IdString" placeholder="Enter id"/>
    <input id="Submit1" name="Submit1" type="submit" value="DoSomething1" />
    <input id="Submit2" name="Submit2" type="submit" value="DoSomething2" />
</form>
@* ..... *@
}

在 MyController 我有 DoSomethingAction 方法。我想调用此方法并在按下按钮时能够看到 IdString:DoSomething1 或 DoSomething2。这是来自控制器的 DoSomethingAction 方法:

 public ActionResult DoSomethingAction()
    {
        string id= Request.Form["IdString"];
        //string button=...

        // ...
    }

当我为 DoSomethingAction 方法设置断点时,我发现它从未被调用过。 我试图为这个方法添加 [Httppost] 属性,但它并没有解决我的问题。

我做错了什么? 之后,如何在 DoSomethingAction 方法中查看按下了哪个按钮?

【问题讨论】:

  • 您的嵌套表单是无效的 html 且不受支持
  • 修复无效的嵌套表单,接受答案,然后返回新问题,也许是关于您遇到的新问题。尽量把问题集中在一个问题上,你可能会得到更好的回应和进步。

标签: c# asp.net-mvc


【解决方案1】:

HTML 表单不能嵌套 HTML 表单。请阅读https://www.w3.org/TR/html5/forms.html#the-form-element

如果您需要多个表单,您可以将它们定义为兄弟姐妹。

【讨论】:

  • 我更改了我的代码。我把表格放在@using (Html.BeginForm()) { } 下。该方法仍然没有被调用,我收到一个错误: "Server Error in '/' Application.The resource cannot be found. Requested URL: /DoSomethingAction" 。我想现在它正在搜索一个名为 DoSomethingAction 的视图,而这不是我想要的......
  • 在应用中找不到路径。确保您的路由正确。如果未找到视图,将显示“.cshtml is not found”。
  • 我试图添加一个新的路由`routes.MapRoute(name: "DoSomethingAction", url: "My/DoSomethingAction", defaults: new { controller = "My", action = "DoSomethingAction", id = UrlParameter.Optional } ); ` 到 RouteConfig。我不确定它是否正确。我想这不是因为我收到了同样的错误
  • @SomeoneNew 尝试在 url 参数中添加 {id}。
【解决方案2】:

使用html.BeginFormtype="Submit"。接下来要记住,html.BeginForm 是一个 post 方法,所以如果你想使用它,给 Action 一个属性,如果你没有说明 view action 应该返回什么,他会假设 view 是与操作同名,在您的情况下为DoSomethingAction,这就是您收到服务器错误的原因。在return View() 中创建该视图或状态您要返回哪个视图(索引或其他)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多