在表单中有多个提交按钮,并确定在控制器中按下了哪些按钮 [英] Have multiple submit buttons in a form and determine which was pressed in a controller

查看:275
本文介绍了在表单中有多个提交按钮,并确定在控制器中按下了哪些按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Spring应用程序中,我有一个jsp,它有一个表单,我希望有多个提交按钮转到同一个控制器。我需要能够确定控制器中按下了哪个按钮。表单向用户显示多个项目,他们可以选择其中一个项目,唯一的区别是所选项目的ID。

In my Spring application, I have a jsp that has a form where I want to have multiple submit buttons that go to the same controller. I need to be able to determine which button was pressed in the controller. The form displays a number of items to the user and they can select one of the items with the only difference being the ID of the selected item.

在jsp中,我我正在创建这样的表单:

In the jsp, I'm creating the form like this:

<form:form method="post" commandName="myCommand">

    <c:forEach items="${model.availableitems}" var="item">
      <span class="item">${item.description}</span> 
      <input type="hidden" name="id" value="${item.ID}"/>
      <input type="submit" name="SelectButton" value="Select" />
    </c:forEach>

  </div> 
</form:form>

然而,这会在日志中给出一个数据绑定错误:1消息,表格不是没有提交给控制器。

However, this gives me a "Data binding errors: 1" message in the log and the form isn't submitted to the controller.

我尝试将myCommand.id从int更改为String,但是提交时的值是id1,id2,id3 ......(所有ID在逗号分隔列表中)无法确定按下了哪个按钮。我不希望必须为每个按钮指定不同的操作,因为项目数量可以增长,并且它们的操作完全相同,只是使用不同的ID。

I tried changing the myCommand.id from an int to a String, but then the value when it's submitted is id1,id2, id3... (all of the IDs in a comma delimited list) with no way of determining which button was pressed. I don't want to have to specify different actions for each button as the number of items can grow, and the action for them is all the same, just with a different ID.

如何在此表单中有多个按钮并获取控制器中的值?

How can I have multiple buttons in this form and get the value in the controller?

推荐答案

为什么不为每个项目使用单独的表格?

Why not just use a separate form for each item?

<c:forEach items="${model.availableitems}" var="item">
  <form:form method="post" commandName="myCommand">
    <span class="item">${item.description}</span> 
    <input type="hidden" name="id" value="${item.ID}"/>
    <input type="submit" name="SelectButton" value="Select" />
  </form:form>        
</c:forEach>

这篇关于在表单中有多个提交按钮,并确定在控制器中按下了哪些按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆