2017-08-07 8 views
0

select.Items.Countを使用しているときに問題が発生しました。選択項目を数えられません

状況1:C#で

<select id="PrimaryArea" style="width: 100px" required tabindex="6" runat="server"> 
    <option value="A">Item1</option> 
    <option value="B">Item2</option> 
    <option value="C">Item3</option> 
    <option value="D">Item4</option> 
</select> 

int PrimaryAreaCount=PrimaryArea.Items.Count // return 4 

状況2:オプションはJavascriptでプログラム

<select id="SecondaryArea" style="width: 100px" required tabindex="7" runat="server"> 
</select> 

を追加:チェックjavascripを使用している場合、正しく返しますC#の中のT

var select = document.getElementById("<%= SecondaryArea.ClientID %>"); 
var js = JSON.stringify(<%= SecondaryTable %>); 
var js2 = JSON.parse(js); 
var len = js2.length; 
var i = 0; 
while (i < len) { 
    var new_option = new Option(js2[i].ref_desc, js2[i].cd); 
    select.options[select.options.length] = new_option; 
    i += 1; 
} 

int SecondaryAreaCount=SecondaryArea.Items.Count // always return 0 

私はC#でSecondaryAreaCountのための正しい答えを得るにはどうすればよいですか?

答えて

0

2番目のシナリオを正しく理解している場合は、空のアイテムリストから開始し、JavaScriptでオプションを追加してください。

この場合、JavaScriptはページがクライアントに提供された後にのみ実行されるため、サーバー側C#コードで正しい数を計算することはできません。

解決策の1つは、追加の隠れた入力を使用してカウント結果をポストバックすることです。

<input id="SecondaryAreaCount" type="hidden" value="0" /> 

<script> 
// your existing JS loop here ... 

var countResult = document.getElementById("SecondaryAreaCount"); 
countResult.value = i; // var i is select.options.length after the while loop 

</script> 
関連する問題