Question

The model binding against the checkboxes doesnt seem to for the list of skills. I understand that javascript is an option, however, right now I amd stuck to jsp/jstl route.

// PersonViewModel.java
public class PersonViewModel {
    private String fullName;
    private Integer experienceInYears

    private List<SkillItemViewModel> skillList;

    /*  getters and setters */
}

// SkillItemViewModel.java
public class SkillItemViewModel {
    private Long skillId;
    private String skillName;
    private Boolean skillSelected;

        /*  getters and setters */

}

// controller GET Action

@RequestMapping("person/edit")
public ModelAndView editPerson (HttpServletRequest request, HttpServletResponse response) {

 /* set the view model from the model and attach it to the Model and View object  */



}

// controller POST Action
@RequestMapping("person/update")
public ModelAndView updatePerson(HttpServletRequest request, @ModelAttribute("personViewModel") PersonViewModel viewModel, BindingResult result){
   /*
    on debugging viewModel.skillList is null
   */
}




// Edit Person jsp code snippet editProfile.jsp
<c:set var="loopVar" value ="0">
<ul>
<c:forEach var="item" items="${personViewModel.skillList}">
<spring:bind path="personViewModel.skillList[${loopVar}].skillSelected">
    <input type="checkbox" name="chkSkill${item.skillId}" ${item.skillSelected?'checked':''}>
    <label for="chkSkill${item.skillId}">${item.skillName}</label>
</spring:bind>    
</c:forEach>
</ul>


<c:set var="loopVar" value ="${loopVar + 1}">
Was it helpful?

Solution

Sounds like a binding issue. Have you tried using Spring's <form:checkbox> tag rather than <spring:bind>? It will automatically generate the checkbox attributes as well as a hidden field that Spring uses to determine whether the checkbox is 'on' or 'off'.

Also, you should use the the varStatus loop variable to keep track of the index.

editProfile.jsp

<ul>
<c:forEach var="item" items="${personViewModel.skillList}" varStatus="status">
    <form:checkbox path="skillList[${status.index}].skillSelected" id="chkSkill${item.skillId}"/>
    <label for="chkSkill${item.skillId}">${item.skillName}</label>   
</c:forEach>
</ul>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top