java Spring MVC 表单标签:是否有添加“无选择”项的标准方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/162497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC Form tags: Is there a standard way to add "No selection" item?
提问by axk
There is a select dropdown and I want to add "No selection" item to the list wich should give me 'null' when submitted. I'm using SimpleFormController derived controller.
有一个选择下拉列表,我想将“无选择”项目添加到列表中,提交时应该给我“空”。我正在使用 SimpleFormController 派生控制器。
protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("countryList", Arrays.asList(Country.values()));
return map;
}
And the jspx part is
而jspx部分是
<form:select path="country" items="${countryList}" title="country"/>
One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to disply this 'null' as 'No selection'. Is there a better solution?
一种可能的解决方案似乎是在列表的开头添加一个空值,然后使用自定义 PropertyEditor 将此“空”显示为“无选择”。有更好的解决方案吗?
@Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution?
@Edit:我已经使用自定义验证注释解决了这个问题,该注释检查所选值是否为“无选择”。有没有更标准、更简单的解决方案?
回答by Jacob Mattison
One option:
一种选择:
<form:select path="country" title="country" >
<form:option value=""> </form:option>
<form:options items="${countryList}" />
</form:select>
回答by skaffman
I don't think you should need a property editor for this. If the "blank" option is first in the list, and the tag that outputs the list doesn't mark any of them as selected, then the browser should select the first, "blank" one automatically.
我认为您不需要为此使用属性编辑器。如果“空白”选项是列表中的第一个,并且输出列表的标签没有将它们中的任何一个标记为选中,那么浏览器应该自动选择第一个“空白”选项。
When you submit the form, try and work it so that the "blank" value is bound to your command as a null, which might happen automatically, depending on the type.
当您提交表单时,尝试处理它,以便将“空白”值作为空值绑定到您的命令,这可能会自动发生,具体取决于类型。

