chetan p
chetan p

Reputation: 57

Access variablea of javascript in .aspx.vb file

I want to access variables defined in Javascript in.aspx file to .aspx.vb file

How can i access variables in .aspx.vb file?

<script type="text/javascript" language="javascript">
   var c=0;
   var m=0;
   var h=0;
   var t;
   var timer_is_on=0;
   function startTMR()
   {  
      document.getElementById('TimeLable').value=h+":"+m+":"+c;
      c=c+1; 
      if(c==60)
      {
         c=0;
         m=m+1;
         if(m==60)
         {
            m=0;
            h=h+1;
         }
      }
      t=setTimeout("startTMR()",1000);
   }

   function doTimer()
   {
      if (!timer_is_on)
      {
         timer_is_on=1;
         startTMR();
      }
   }

This is simple javascript I'm using in my .aspx page

now i want to access the variable h m and c in .aspx.vb page how to do that?

Upvotes: 1

Views: 683

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83358

You'll need to save that javascript variable into a hidden input, which will post with your form when you do a postback. You'll be able to access the value via:

string value = Request.Form["hiddenName"];

Assuming you declare your hidden input like this:

<input type="hidden" id="hiddenValue" name="hiddenName" />

You can set this value like this with native JavaScript:

document.getElementById("hiddenValue").value = "12";

or with jQuery like this:

$("#hiddenValue").val("12");

If you'd like to make sure this hidden input is automatically saved to the JavaScript variable x before you post back, you could do the following with jQuery

$("#form1").submit(function () {
     $("#hiddenValue").val(x);
});

Or this with native JavaScript:

document.getElementById("form1").addEventListener("submit", function () {
       document.getElementById("hiddenValue").value = x;
});

If you're not using jQuery, and you opt for this native option, just make sure you put the script at the bottom of the body section; do not put this script in the head, since the dom is not formed yet, and you will get a null error.

And obviously this all assumes your form element looks like this:

<form id="form1" runat="server">

if yours has a different id, then adjust accordingly.

Upvotes: 2

Related Questions