Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a JavaScript variable from code behind in asp.net

i am using a JavaScript and it have the below code:

<script type="text/javascript">
var count = 0;

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

so if its click the value is added by 100 i check using an alert, now how to access the var count in my code-behind

like image 881
Krish Avatar asked Mar 01 '12 12:03

Krish


People also ask

How Pass value from JavaScript to code behind in VB net?

How to Pass Values from JavaScript to CodeBehind? You can also use a HTML INPUT control by setting runat="server". This is another way where we can make an Ajax call to server whenever we need the server value in javascript/jquery. When you use ASP.Net AJAX then you can use PageMethods for this.

How use jquery variable in C# code?

click(function () { var btn = $(this). attr('id'); alert(btn); $. ajax({ type: 'GET', url: '@Url. Action("ActionName", "ControllerName")', data: { id: btn }, success: function (result) { // do something } }); });


1 Answers

You will need to store the count variable on a server-side control in order to do this.

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-behind simply use:

int value;
if (Int32.TryParse(example.Value, out value))
{
     // Do something with your value here
}
like image 67
Meryovi Avatar answered Nov 12 '22 19:11

Meryovi