2014-04-10 49 views
1

我想在頁面加載的下拉菜單中顯示選定的值。 我的編輯頁面顯示值,國家。現在用戶屬於美國,因此在頁面加載時應默認選擇美國。我可以使用JavaScript或jQuery。顯示在頁面加載編輯jsp頁面上的下拉列表中選定的值(Spring MVC)

我在互聯網上找到了一些幫助,但他們與scriplets(<%%>),我不想使用它們。

我傳遞一個具有Id和Value的List。另外我還有另一個對象。 我可以通過在jsp中引入for循環並顯示值來編寫代碼,但可能是我在那裏犯了一些錯誤。也想知道是否有更好的方法來做到這一點。

我正在使用Spring MVC。

謝謝。

回答

5

「現在用戶屬於美國,因此在頁面加載時應默認選擇美國。」你知道手邊的用戶屬於某個國家。

假設你有一個POJO國家爲:

public class Country{ 
     String countryName; 
     String countryId; 
     //setters and getters 
    } 

    public class YourForm{ 
     List<Country> countryList; 
     String selectedCountryId; 
     ... 
     //setters and getters 
    } 

在你的控制器的方法委託給JSP:

... 
    YourForm form = new YourForm(); 
    //set your countrylist to form 
    //set country user belongs to - selectedCountryId - since you know before hand user belongs to some country. 
    model.addAttribute("yourForm", form): 
    ... 

現在訪問它在JSP爲:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> 
    </head> 
    <body> 
    <form:form id="yourForm" modelAttribute="yourForm" method="post"> 

    <tr> 
     <td width="50%" class="label"> 
      <form:select id="countryId" path="selectedCountryId" title='Select Country'> 
       <option value="">Please Select</option> 
       <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName"/> 
      </form:select> 
     </td> 
    </tr> 
    </body> 

由於selectedCountryId已經在控制器中設置,您將在jsp中看到該國家爲自動選擇的國家。

+0

謝謝。工作得很好。我正在使用<選擇標記.....用 romhail

相關問題