简体   繁体   中英

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. the loop execute correctly but my c# variable not Initialize again. 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. It is possible using write FOR loop also in your .ASPX page.

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:

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:

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

Please let me know if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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