thymeleaf下拉选框从后台List集合加载选项并回显选中值

页面模板:thymeleaf

控件:下拉选框

需求点:1、select中的option动态从后台读取;

              2、执行修改时,下拉选框将从后台查到的值回显在选框中,并加载其他选项。

针对第一点需求,实现代码如下:

<div class="form-group">    
	<label class="col-sm-3 control-label">故障所属类别:</label>
	<div class="col-sm-8">
		<select name="faultTypeName" id="faultTypeName" lay-verify="required" class="form-control">
			<option th:each="faultType:${faultTypes}" th:value="${faultType.id}" th:text="${faultType.typeName}"></option>
		</select>
	</div>
</div>

关键代码:

<option th:each="faultType:${faultTypes}" th:value="${faultType.id}" th:text="${faultType.typeName}"></option>

其中faultTypes为后台传递过来的集合,faultType为集合对应的对象,下拉选框是显示中文名称,所以这里的text为Name,但传到后台需要取的是id值。

针对第2个需求点,只需在上面基础上,在options选项中添加以下代码:

th:selected="${faultPhenomenon.faultTypeName  eq faultType.typeName}"

其中faultPhenomenon为后台传递过来对象名,faultTypeName为对象的属性,而faultType为集合List的对象,typeName为集合List的对象的属性,如果再者值一致,则标注为选中状态。

发布了137 篇原创文章 · 获赞 28 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/shenxiaomo1688/article/details/104553313