Green Fireman
Green Fireman

Reputation: 697

Spring MVC keep selected value in select tag

I have 2 select tags in my jsp:

First one:

<select name="performers">
    <option value="all" label="All performers">All performers</option>
    <c:forEach var="list" items="${list}">
        <option value="${list}">${list}</option>
    </c:forEach>
 </select>

Second one:

<select name="period">
    <option value="0"> </option>
    <option value="1">Last Qtr</option>
    <option value="2">Last Month</option>
    <option value="3">Last Calendar Year</option>
    <option value="4">Current Year to Date</option>
    <option value="5">Current Qtr to Date</option>
    <option value="6">Current Month do Date</option>
</select>

How can I keep the selected value of this combobox from the controller after the page reloads (post method)?

Upvotes: 2

Views: 4810

Answers (1)

Prasad
Prasad

Reputation: 3795

M. Deinum pointed correctly. Use form model and spring form tags. Assuming your form to contain fields as:

    public class YourForm{
        //Assuming thedatatype of performersList as String
        List<String> performersList;
        String performers;
        ...
        //setters and getters
    }

In your controller method which delegates to the jsp:

    ...
    YourForm form = new YourForm();
    //set your performersList in form 
    //set  performers in form - the selected value to be displayed in view
    model.addAttribute("yourForm", form):
    ...

Now access it in jsp as:

    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <body>
    <form:form id="yourForm" modelAttribute="yourForm" method="post">
    <tr>
        <td >
            <form:select id="performers" path="performers" title='Select Performers'>
                <option value="">All performers</option>
                <form:options items="${performersList}"/>
            </form:select>
        </td>
    </tr>
    </body>

Since performers is already set in controller you will see that performers as auto selected in the jsp. Similarly you can do it for other dropdown option.

Hope this helps.

Upvotes: 4

Related Questions