简体   繁体   English

从javascript重新初始化c#变量

[英]initialize again c# variable from javascript

i have ac# variable that declare in aspx page and want to Initialize again it in a for(;;) loop. 我有一个在aspx页中声明的ac#变量,并希望在for(;;)循环中再次对其进行初始化。 the loop execute correctly but my c# variable not Initialize again. 循环正确执行,但我的c#变量未再次初始化。 what i am doing!! 我在做什么!!

 for (var j = 2; j < '<%=menu[i].Length%>'; j++) {
                                var flag = <%=j++%>
                                alert(flag);
                            }

but in below code it is possible 但是在下面的代码中

for (var j = 2; j < '<%=menu[i].Length%>'; j++) {                               
                                <%j++;%>
                                <%j++;%>
                                var flag = <%=j%>
                                alert(flag);
}

Alernate way is using hidden field rather than using variable. 另一种方法是使用隐藏字段而不是使用变量。

 <asp:HiddenField runat="server" ID="hdn" />

var myVal = document.getElementById("<%= hdn.ClientID %>").value;
for (var j = 2; j < '<%=menu[i].Length%>'; j++)     {                               
    myVal++;
    document.getElementById("<%= hdn.ClientID %>").value = myVal;

}

On serverside: 在服务器端:

int val = int.Parse(hdn.Value);

Yes you can initialize your code behind variable in your .ASPX page. 是的,您可以在.ASPX页中的变量后面初始化代码。 It is possible using write FOR loop also in your .ASPX page. 也可以在.ASPX页面中使用write FOR循环。

Code behind variable must be public and member variable of your class: 变量后面的代码必须是您的类的公共变量和成员变量:

public partial class _Default : System.Web.UI.Page
{
     public int i = 0;

     protected void Page_Load(object sender, EventArgs e)
     {

     }
}

Javascript Function: JavaScript函数:

function increaseVariable() {
        <% for (int j = 2; j < menu[i].Length; j++)
           {
            %>
        var flag = <%=i++%>; 
            alert(flag);
        <%}%>
    }

You can test your functionality to add below input button and call above function in onclick event: 您可以测试您的功能以在输入按钮下方添加并在onclick事件中调用上方功能:

<input type="button" value="Increase" onclick="increaseVariable();" />

Please let me know if you have any questions. 请让我知道,如果你有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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