How to pass a variable from asp.net to JavaScript?
Create a property in your code behind
protected string MyProperty { get { return "your value"; } }
then in javascript
var myValue = "<%= MyProperty %>";
There are a number of ways:
1 - Write it out in your JavaScript with <%= myVariable %>
2 - Set a cookie server-side and then retrieve the cookie client side
3 - Set a hidden form input to your value
4 - Redirect to your page with the value as a querystring parameter, and then parse the params using JavaScript
5 - Build all your JavaScript server-side, save to a variable, and then write out the variable client-side.
6 - Retrieve the value with an AJAX request
You can use an ASP.Net HiddenField. You just set its value on the server and retrieve it via javascript when you need it.
Serverside
hdf_Test.Value = "yourValue";
HTML
<asp:HiddenField runat="server" ID="hdf_Test" />
Javascript
document.getElementById('hdf_Test').value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With