passing data between (c#) and javascript

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

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

To pass a variable from Javascript to, 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;
<form id="formElement" method="POST" action="asppage.aspx">
     <input type="hidden" id="formElementVar1" value="" />

Open in new window

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%>')
so I need to populate a hidden form field with the c# variable and have javascript read it?
You have to pass the ClientID into a Javascript variable, then use that to get the form field by id.  The "HiddenFormField" is the 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;

Open in new window

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.