You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grails 3.3.x多选<g:select>绑定List单值为空的问题

Grails 3.3.x 多选<g:select>单选时List绑定失败的解决方案

问题原因

表单提交多选组件时,选择多个值会以字符串数组形式传递参数,选择单个值则传递单个字符串,而Grails默认数据绑定不会自动将单个字符串转换为List类型,导致单选时Command对象的List属性为空。

解决方法

方法一:修改前端组件的name属性

将<g:select>的name属性改为star[],强制浏览器无论单选还是多选都以数组形式提交参数,Grails就能正确绑定到List:

<g:select id="star" name="star[]"
          from="${[['name': '5 star', 'id': '5'], ['name': '4 stelle', 'id': '4'], ['name': '3 stelle', 'id': '3'], ['name': '2 stelle', 'id': '2'], ['name': '1 stelle', 'id': '1']]}"
          value="${currentStarValue}"
          optionKey="id" optionValue="name"
          multiple="multiple" class="form-control select2" style="width: 100%;"/>

方法二:在Command对象中自定义setter方法

给SimpleCommand添加自定义的setStar方法,处理单个字符串和数组两种情况:

class SimpleCommand implements Validateable {

    String filter
    List lFilter = []
    List star
    long id

    void setStar(Object value) {
        if (value instanceof String) {
            star = [value]
        } else if (value instanceof List) {
            star = value
        } else {
            star = []
        }
    }
}

方法三:使用@BindUsing注解定制绑定逻辑

通过Grails的@BindUsing注解直接在字段上定义绑定规则:

import grails.databinding.BindUsing

class SimpleCommand implements Validateable {

    String filter
    List lFilter = []
    
    @BindUsing({ obj, source ->
        def starValue = source['star']
        starValue instanceof List ? starValue : (starValue ? [starValue] : [])
    })
    List star
    
    long id
}

以上三种方法都能解决单选时List绑定为空的问题,可根据项目需求选择合适的方案。

内容的提问来源于stack exchange,提问作者NiBE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:15:39