【问题标题】:MVC4 - One form 2 submit buttonsMVC4 - 一个表单 2 提交按钮
【发布时间】:2024-01-23 09:36:01
【问题描述】:

我按照这篇文章的说明进行操作: Asp.net mvc3 razor with multiple submit buttons 这是我的模型:

public class AdminModel
{
  public string Command { get; set; }
}

我的控制器

[HttpPost]
public ActionResult Admin(List<AdminModel> model)
{
   string s = model.Command;
}

我的观点

@using (Html.BeginForm("Admin", "Account"))
{
  <input type="submit" name="Command" value="Deactivate"/>
  <input type="submit" name="Command" value="Delete"/>
}

当我回帖时,字符串“s”始终为空。

我还在此论坛帖子中尝试了第二个答案(获得 146 票的那个):How do you handle multiple submit buttons in ASP.NET MVC Framework?,这也是空的。我做错了什么?

【问题讨论】:

标签: asp.net-mvc forms submit


【解决方案1】:

您需要通过按钮名称从他们的服务器端获取值,

public ActionResult Admin(List<AdminModel> model,string Command)
{
   string s = Command;
}

【讨论】:

  • 哇,我以为我试过了,根据我帖子的第二个论坛。我不知道那次我做错了什么。现在可以了,谢谢。
  • 请注意,当使用&lt;button&gt; 标签而不是&lt;input&gt; 标签时,在表单字段之一中按 Enter 键,Command 参数将不会设置,因此将是 null。您可以通过使用 Javascript 来捕获按键事件,或者通过在控制器操作中设置默认值来处理它:public ActionResult Admin(List&lt;AdminModel&gt; model, string Command = "Deactivate")
【解决方案2】:

从我在发布的代码中可以看到,您不会向控制器发送模型列表,而只是发送一个模型实例。尝试将控制器修改为:

[HttpPost]
public ActionResult Admin(AdminModel model)
{
   string s = model.Command;
}

【讨论】:

  • 我的观点是在一个 AdminModel 列表中:)。