【问题标题】:thymeleaf: th:value is ignored when using th:fieldthymeleaf:使用 th:field 时忽略 th:value
【发布时间】:2015-03-07 16:30:59
【问题描述】:

我有一个表单,我想在其中编辑一些用户数据。 因此,已经存储的数据被放置为 th:value 并在发送后我使用 spring 验证进行验证,并希望在错误输入时返回表单。我希望输入字段具有用户输入的值,但它总是给我存储的输入。

这就是输入字段的样子

<input type="text" th:value="${product.name}" th:field="*{name}" th:errorclass="fieldError"/>

如果第一次加载表单,输入字段应该具有已存储数据的值。

如果在提交后加载并出现验证错误,则输入字段应具有用户输入的值。

有办法解决吗?

谢谢!

【问题讨论】:

  • 你为什么使用 th:value?最后一个问题的答案是只使用th:field,你可以试试吗?
  • 因为我想在加载存储的数据时设置值。
  • 但是,如果您正在使用表单并在控制器中填充产品对象,那将可以正常工作。你能包括你的表单和你的控制器的代码吗?

标签: thymeleaf


【解决方案1】:

如果在验证错误后输入值错误,则您的控制器中有错误(您为 *{name} 设置了错误的值)。

【讨论】:

    【解决方案2】:

    因为属性 th:field 是 th:name 和 th:value 的组合 所以,要么使用这个:

    <input type="text" th:value="${product.name}" th:name="name" th:errorclass="fieldError"/>
    

    或者这个:

    <input type="text" th:field="*{name}" "th:errorclass="fieldError"/>
    

    【讨论】:

      【解决方案3】:

      使用 th:field 或 value,id 和 name 是可以的。如果你使用 th:field,你可以这样写:

      <input type="text" th:field="${product.name}" th:value="${product.name}" "th:errorclass="fieldError"/>
      

      【讨论】:

        【解决方案4】:

        属性 th:field 将替换 inputvalueidname /strong> 标签。

        改为使用普通的 th:idth:valueth:name,而不使用 th:field。然后你会得到你想要的。

        然后会是这样的:

        <input type="text" th:value="${product.name}" th:name="name" th:id="name" th:errorclass="fieldError"/>
        

        类似的答案在这里:How to set thymeleaf th:field value from other variable

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-11
          • 1970-01-01
          • 2013-12-20
          相关资源
          最近更新 更多