你真的不能相互交織您的客戶端JavaScript代碼和你這樣的服務器端的C#代碼。基本上,一旦在你的頁面上完成了渲染,你就不會訪問服務器,直到發生PostBack
或者你使用AJAX調用一個暴露的WebMethod
。
頁面最初呈現時會調用它,否則,您需要使用其他技術之一。
WebMethod
方法
,因爲我通過採取WebMethod
,將涉及您創造您的一個方法的優點前面提到你可以做到這一點的代碼隱藏看起來是這樣的:
[WebMethod]
public static void IncrementCounter()
{
// Since you want to return the incremented value, use ++counter
return ++counter;
}
然後,您需要在ASPX頁面中添加一個引用到jQuery庫,該庫將用於處理執行AJAX調用以訪問此服務器端方法:
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
// This will ensure that your jQuery code is ready to run
$(function(){
// When the page is ready, call your loading function
loader();
});
function loader() {
for(var i=0; i< <%=array1.Length%>; i++){
// This will call your WebMethod
$.post('YourPage.aspx/IncrementCounter', function(count){
// count will contain the counter value
alert(count);
});
}
}
</script>
你是什麼實際問題? –