【问题标题】:Dynamic row thymeleaf动态行百里香
【发布时间】:2019-11-21 09:12:46
【问题描述】:

我想在 Thymeleaf 和 Spring Boot 中创建动态添加和删除列表行。 我不知道如何在动态行中使用百里香,但我正在尝试这样做 所以这是我的代码:

public class Form{
    private List<Obj> list = new ArrayList<>();
//...
}


public class Obj{
   private String a;
}

控制器:

 @GetMapping("/form")
    public String form(Model model) {
        model.addAttribute("form", new Form());
        return "/form";
    }

HTML:

[...]
<form class="form-horizontal row-border" action="#" th:action="@{/form}" th:object="${form}" method="post">
    <div class="form-group">
        <div class="col-md-12">
            <div class="row">
                <label class="col-md-2 control-label">...</label>
                <div class="col-md-10">
                    <table id="myTable" class=" table order-list">
                        <thead>
                        <tr>
                            <td>String</td>

                        </tr>
                        </thead>
                        <tbody>
                        <tr th:each="row:${list}">
                            <td class="col-sm-1">
                                1
                            </td>
                            <td class="col-sm-3">
                                <input th:field="*{list[__${row.index}__].a}" type="text" name="xyz"  class="form-control"/>
                            </td>

                        </tr>
                        </tbody>
                        <tfoot>
                        <tr>
                            <td colspan="5" style="text-align: left;">
                                <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add row" />
                            </td>
                        </tr>
                        <tr>
                        </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>                   
</form>

[...]

但我不知道如何从表单向控制器发送数据

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

    控制器根据输入名称接收您的数据。 th:field 以正确的方式设置您的输入名称,以便控制器接收它。

    遗憾的是,如果您在客户端中添加一个新行,其中 thymeleaf 不再存在,您必须手动设置正确的名称。您可以使用这样的 js 函数(或任何其他方式)查找要在新行输入中设置的名称:

    var nextRow = 0;
    
    while($("input[name='list[" + nextRow + "].a']").length){
        nextRow ++;
    }
    

    nextRow 将有下一个空闲行,只需使用它以 thymeleaf 生成的方式构建名称并将其设置为新输入的名称。

    【讨论】:

    • 不太明白,能不能写个例子?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 2018-02-03
    • 2016-01-04
    相关资源
    最近更新 更多