【问题标题】:input type="submit" doesn't trigger HttpPost in MVC?input type="submit" 不会触发 MVC 中的 HttpPost?
【发布时间】:2016-01-08 16:21:11
【问题描述】:

我开始感到困惑。我刚开始建立一个网站,偶然发现我的控制器有问题。它根本不发布,有或没有参数。我想补充一点,我刚刚从另一个控制器和视图中移动了 ActionResult 方法。这可能是显而易见的事情,但累了,我想我会要求澄清!

视图路径/名称:视图/表/注册

@foreach (var registration in ViewBag.AllRegistrations)
    {
      using (Html.BeginForm("Registrations", "Table", new { regid = registration.RegistrationId }))
      {
         <tr class="odd gradeX">
          <td>
            <input type="submit" name="command" value="Edit" class="btn btn-default btn-xs" />&nbsp;
            <input type="submit" name="command" value="Delete" class="btn btn-default btn-xs" />
          </td>
         </tr>

      }
    }

控制器名称:TableController

public ActionResult Registrations()
{
    ViewBag.AllRegistrations = registration.SelectAll();
    return View();
}

[HttpPost]
public ActionResult Registrations(int regid, string command)
{
    //doesn't post
    return View();
}

路由配置:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Table", action = "Registrations", id = UrlParameter.Optional }
    );
}

谢谢:)

【问题讨论】:

  • 你可以在 View() 上执行 Ctrl M + Ctrl G 吗? (带有HttpPost的那个)。这将指示您要显示的视图。
  • 不相关,但您的路线有{id},但在您的BeginForm() 和POST 方法中您有regid 如果您想匹配您的,您应该使用new { id = registration.RegistrationId }Registrations(int id, string command)路线(或将 {id} 更改为 {regid} 并使其成为 regid = UrlParameter.Optional
  • 这一切都在 &lt;table&gt; 元素内 - 在这种情况下,您的 html 无效(&lt;form&gt; 元素不是 &lt;table&gt; 的有效子元素
  • 这是我的问题 Stephen Muecke!感谢您指出。

标签: asp.net-mvc post submit


【解决方案1】:

[HttpPost] 公共 ActionResult 编辑(int regid,字符串命令) {

//Insert some logic

}

您可以将操作/方法名称设置为与按钮“值”相同,而不是设置默认路由

这可能会使您的代码更具可读性,因为您可以拥有称为创建、编辑、删除等操作/方法。希望对你有帮助

还有你的帖子逻辑/代码在哪里?目前,您的发布操作只是返回一个视图。你想用那种方法做什么?

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多