Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable from ASP.net to JavaScript

How to pass a variable from asp.net to JavaScript?

like image 503
user1363918 Avatar asked May 10 '12 18:05

user1363918


3 Answers

Create a property in your code behind

protected string MyProperty { get { return "your value"; } } 

then in javascript

var myValue = "<%= MyProperty %>"; 
like image 118
Habib Avatar answered Oct 04 '22 22:10

Habib


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

like image 29
D'Arcy Rittich Avatar answered Oct 04 '22 21:10

D'Arcy Rittich


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
like image 36
Josh Mein Avatar answered Oct 04 '22 22:10

Josh Mein