对不起一个愚蠢的问题,但我不太明白会发生什么,如果这是我怀疑的......好吧,我真的很茫然。
我正在使用 spring boot + thymeleaf + materialize css 来显示和验证表单。
现在,在我看到的许多示例中,我没有遇到的是这种情况:
一些表单域是预填充的,对客户来说应该是禁用的,显示它们的预填充值。这个预填充发生在 Controller 中,而我处理一些其他请求,并重定向到这个 View
我正在使用这样的 th:object 将 pojo 绑定(bind)到表单
<form id="register_form" action="#" th:action="@{/showform}" th:object="${userInfo}" method="post">
<div class="input-field">
<label th:text="#{label.surname}" for="surname"></label>
<input type="text" th:field="*{surname}" id="surname" th:attr="value=${userInfo.surname}" />
</div>
<div class="input-field">
<label th:text="#{label.name}" for="givenname"></label>
<input type="text" th:field="*{givenname}" id="givenname" th:attr="value=${userInfo.givenname}" disabled="disabled" />
</div></form>
并像这样在 Controller 的 POST 处理程序中获取它:
@RequestMapping(value = {"/showform"}, method = RequestMethod.POST)
public ModelAndView submitFormPage(@ModelAttribute("userInfo") @Valid UserInfo userInfo,
BindingResult bindingResult, RedirectAttributes redir)
{
ModelAndView mview = new ModelAndView();
if (bindingResult.hasErrors())
{
// show form again with error messages
mview.addObject("userInfo", userInfo);
mview.setViewName("/showform");
}
else
{
// ...
}
return mview;
}
RedirectAttributes 的存在是出于其他一些原因。如您所见,表单上有两个元素,第一个启用,第二个禁用。
它们的值使用来自 POJO 的预填充值正确填充,我通过 ModelMap 传递到 View 。我也可以在 GET 处理程序中跟踪它。
但是我从 View 中返回的 ModelMap 包含上述 POJO,其值为 NULL,而不是绑定(bind)到禁用控件的元素。我希望它们由 value 属性的内容填充,即使这些控件被禁用。启用的控件可以正常携带它们的值。
还是仅仅是禁用的控件根本不包含在回发中?如果是这种情况,你会建议我怎么做?一些人建议添加一个晦涩的 CSS 来“伪造”禁用控件的行为。还是我错过了一般接线中的某些内容?
我对可能的解决方法感到恐惧-但我一定做错了什么.. th:attr 是我尝试过的解决方法之一,但似乎没有奏效。我也尝试使用 th:id 和 th:disabled 但它也没有帮助。
最佳答案
这里有个误区我想想disabled
的使用.
A
readonly
element is just not editable, but gets sent when the according form submits. adisabled
element isn't editable and isn't sent on submit. Another difference is thatreadonly
elements can be focused (and getting focused when "tabbing" through a form) whiledisabled
elements can't.
More detailed comparison
所以要回答你的问题:你应该选择
readonly
如果你想将你的属性绑定(bind)到你的 pojo
并且用户仍然无法编辑它们。
关于带有禁用输入的 Spring 模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163627/