首页 > 解决方案 > 按下表单中的按钮时如何从控制器调用方法?

问题描述

主要问题是当我按下按钮时没有调用来自控制器的方法。我在 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 方法中查看按下了哪个按钮?

标签: c#asp.net-mvc

解决方案


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

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


推荐阅读