SpringBoot项目,前端使用Thymeleaf,要实现一个select下拉控件自动选中的功能。具体步骤是后端传递下拉列表需要加载的数据集合,以及当前需要被选中的值,前端select中使用Thymeleaf的th:field自动判断并选中下拉控件:
错误代码(使用字符串传递值userId,这里前端判断无效):
/**
* 新增员工
*/
@GetMapping("/add")
public String add(ModelMap modelMap)
{
modelMap.put("userId", "test_id_00001");//直接返回字符串
List<Media> mediaList = sysUserService.selectMediaList();
modelMap.put("mediaList", mediaList);
return prefix + "/add";
}
前端使用 th:field 进行自动选中的判断(这里使用字符串userId无效):
<div class="col-sm-8">
<select name="media_id" id="media_id" class="selectpicker" title="请选择媒体" data-live-search="true" >
<option th:each="media : ${mediaList}" th:text="${media.mediaName}"
th:value="${media.mediaId}" th:field="${userId}" ></option>
</select>
</div>
正确代码(使用对象user传值,前端使用对象属性取值):
/**
* 新增员工
*/
@GetMapping("/add")
public String add(ModelMap modelMap)
{
SysUser tempUser = new SysUser();
tempUser.setUserId("test_id_00001");
modelMap.put("user", tempUser);
List<Media> mediaList = sysUserService.selectMediaList();
modelMap.put("mediaList", mediaList);
return prefix + "/add";
}
前端使用 th:field 进行自动选中的判断(使用user对象属性取值user.userId ):
<div class="col-sm-8">
<select name="media_id" id="media_id" class="selectpicker" title="请选择媒体" data-live-search="true" >
<option th:each="media : ${mediaList}" th:text="${media.mediaName}"
th:value="${media.mediaId}" th:field="${user.userId}" ></option>
</select>
</div>

该博客围绕SpringBoot项目展开,前端采用Thymeleaf,旨在实现select下拉控件自动选中功能。后端需传递下拉列表数据集合与当前选中值,前端用Thymeleaf的th:field判断选中。还给出错误代码(用字符串传值判断无效)和正确代码(用对象传值并取属性值)。
3万+





