passing data between asp.net (c#) and javascript

Is it possible to pass variables from asp.net to javascript and the other way around?
Mr_ShawAsked:
Who is Participating?
 
ChetOS82Connect With a Mentor Commented:
You can "pass" a variable from ASP.net into javascript like this

<script type="text/javascript">
var jsVariable = '<%=aspVariable%>';
</script>

To pass a variable from Javascript to ASP.net, you would have to store the variable in a FORM, and then submit the form.
<script type="text/javascript">
function passToAspNet() {
    document.getElementById('formElementVar1').value = jsVariable;
    document.getElementById('formElement').submit();
}
</script>
<form id="formElement" method="POST" action="asppage.aspx">
     <input type="hidden" id="formElementVar1" value="" />
</form>

Open in new window

0
 
sm394Commented:
you can do that through hidden fields
Assign  value to Hidden Fileld which you can access on client side with Javascript like this
var s=document.getElementById('<%=hdnTest.ClientID%>')
0
 
vicominCommented:
so I need to populate a hidden form field with the c# variable and have javascript read it?
0
 
ChetOS82Commented:
You have to pass the ClientID into a Javascript variable, then use that to get the form field by id.  The "HiddenFormField" is the ASP.net ID of the field.  The field must be set to runat server.  I haven't tested this.  If you need more information open a new question:
<script type="text/javascript">
var jsFieldId = '<%=HiddenFormField.ClientID%>';
var jsField = document.getElementById(jsFieldId);
var jsFieldValue = jsField.value;
alert(jsFieldValue);
</script>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.