Spring MVC: <form:select> option won't stay selected

后端 未结 1 753
自闭症患者
自闭症患者 2021-01-06 18:09

I have a simple form for adding a new teacher. I\'m using Spring in my view to show a list of teacher\'s titles, but when I select an option

1条回答
  •  别那么骄傲
    2021-01-06 18:30

    Your model includes an attribute title that refers to a Title class. This is not the same title you are referring to in your form, which is actually a titleId. Since the titleId is not part of the modelAttribute, it should be excluded from the tags. You are going to need to use a plain-old tag, you can't just set the value attribute with JSTL, so you have to conditionally set the seelcted attribute of the option, based on the titleId value (if it is set). If titleList is a simple list of Title objects, you can create your

    In your controller, the @RequestParam annotation will pull the titleId out of the submitted data. Since it is not part of the modelAttribute, you need to make sure this gets added as a model attribute:

    ...
    if (result.hasErrors()) {
        if (titleId != null) {
            model.addAttribute("titleId", titleId);  // <--This line added
            model.addAttribute("titleList", titleService.getAll());
            Title title = titleService.get(titleId);
            teacher.setTitle(title);
            model.addAttribute("teacher", teacher);
            return "addTeacher";
        }
        else {
            model.addAttribute("titleList", titleService.getAll());
            return "addTeacher";
        }
    }
    ...
    

    Hopefully we got it this time.

    0 讨论(0)
提交回复
热议问题