【问题标题】:Persist radio checked value in Thymeleaf Spring在 Thymeleaf Spring 中保持无线电检查值
【发布时间】:2018-01-27 19:12:26
【问题描述】:

搜索时,如果我们选择要在其中搜索并提交的给定字段,我们的选择就会被遗忘。有人如何修改视图模板以在显示结果时保持先前的搜索字段被选中?

我已经阅读了许多其他 SO 问题和thymeleaf documentation here,但还没有找到合适的答案。

可以使用以下内容对字符串(如雇主)进行硬编码:

search.html sn-p

<span th:each="column : ${columns}">
  <input
    type="radio"
    name="searchType"
    th:id="${column.key}"
    th:value="${column.key}"
    th:checked="${column.key == 'employer'}"/>

    <label th:for="${column.key}" th:text="${column.value}"></label>
 </span>

SearchController.html sn-p

@RequestMapping(value = "")
public String search(Model model) {
    model.addAttribute("columns", columnChoices);
    return "search";
}

如何在 Thymeleaf Spring 的 POST 中保留用户选择的单选值? (并且默认为第一个,GET 上的值)

【问题讨论】:

    标签: spring spring-mvc spring-boot thymeleaf


    【解决方案1】:

    http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#creating-a-form

    命令对象。

    public class Search {
        // default "employer"
        private String type = "employer";
    
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    }
    

    控制器

    @GetMapping
    public String search(Model model) {
        model.addAttribute("columns", columnChoices);
        model.addAttribute("search", new Search());
        return "search";
    }
    
    @PostMapping
    public String search(@ModelAttribute Search search) {
        // Search's attributes match form selections.
    }
    

    将搜索作为您的命令对象,单选按钮应如下所示:

    <form th:object="${search}">
        <th:block th:each="column: ${columns}">
            <input type="radio" th:value="${column.key}" th:id="${column.key}" th:field="*{type}" />
            <label th:for="${column.key}" th:text="${column.value}" />
        </th:block>
    </form>
    

    【讨论】:

    • 感谢您的帮助,但我并没有试图将雇主作为唯一的领域,我试图保留用户从 5 个单选选项中选择的任何内容,以便在用户发布后坚持,如果他们只是使用 GET,则默认为第一个选项。
    • 我从 .csv 中提取列。
    • 这并没有真正改变答案。您可以有多个具有不同values(和相同th:field)的单选按钮。无论选择哪一个无线电都是POSTed。如果column 不是您的命令对象的正确选项,那么您应该创建一个。
    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 2023-03-27
    • 2021-09-23
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多