var count = 0...">

How to access JavaScript variable from code in asp.net

I use JavaScript and has the following code:

<script type="text/javascript"> var count = 0; jQuery('td').click(function () { if ($(this).hasClass('process')) { count = count+100; alert('count'); } }); </script> 

therefore, if his click adds the value 100 i, check with a warning, now how to access var count in my code.

+4
source share
4 answers

To do this, you will need to save the count variable on the server control.

Example:

 <script type="text/javascript"> var count = 0; jQuery('td').click(function () { if ($(this).hasClass('process')) { count = count + 100; alert(count); // Store the value in the control $('#<%= example.ClientID %>').val(count); } }); </script> <asp:HiddenField ID="example" runat="server" /> 

Then in your code just use:

 int value; if (Int32.TryParse(example.Value, out value)) { // Do something with your value here } 
+13
source

Try the following:

Add a HiddenField and pass the count value to the HiddenField from jQuery

 $(function() { var count = 100; $("#Button1").click(function() { $("#HiddenField1").val(count); }); }); 
+2
source

JavaScript is a client-side technology. The code runs on the server. You cannot directly access javascript variables in your code. You will need to send information to the server, for example, sending them back in the form of form fields or query string parameters using an ajax request.

jQuery is a great library that simplifies the task of sending ajax requests, but many others also exist.

+1
source

Your counter variable is not visible on the server, so you must let it read in some way ... The appropriate solution depends on how you should handle this in the code, maybe it could be setting the count value to a hidden input field which is then sent to the server ...

+1
source

Source: https://habr.com/ru/post/1399174/


All Articles