简体   繁体   中英

How to pass a list from the view to the controller in Spring MVC with thymeleaf?

I have an html page to edit a list of persons. When the page is opened the controller gets the list of persons from the db and binds to the view. That works fine.

Then the user edits the data and clicks save. Now I need to submit the edited data of each person to the controller so that the controller can save the edits.

I'm trying to do that using @ModelAttribute ArrayList<Person> as shown below but it's not working. The arraylist comes empty.

How do I do for the arraylist to come filled with all of the persons objects from the form?

View

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<form action="editperson" method="post">
<th:block th:each="person : ${personBind}">

    Name:
    <input type="text" th:value="${person.name}" />
    </br></br>

    Age:
    <input type="text" th:value="${person.age}" />
    </br></br>

</th:block>
</br></br>
<input type="submit" name="btnSaveEdit" value="Save"/>
</form>

Controller

@RequestMapping(value = "/editperson", params = "btnSaveEdit", method = RequestMethod.POST)
    public String saveEditPerson(@ModelAttribute ArrayList<Person> personsList){
        //save edit code here
        return "editperson";
    }

Spring MVC with Thymeleaf does indeed use model attributes to store data for the Thymeleaf pages. This guide shows how to load data from a form into the application. Try wrapping the ArrayList inside of a custom object and access the list via that object as a ModelAttribute rather than working with an ArrayList directly.

The saveEditPerson method should probably be named "saveEditPersons" since you are parsing a list of persons rather than just one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM