Passing Variable Values From C# To Javascript
Solution 1:
When I need to pass variables into JavaScript I usually I prefer var clientVariable = '<%=ServerVariable%>';
solution. This method is sufficient for small number of scalar variables. If you need to pass a complex object or a array, consider to use JavaScriptSerizlizer
.
The behavior you are having it might happen for number of reasons. One of them might occur, if you have included a scriptlet into .js
file, and not into .aspx
file.
Here is how I would do this:
webgl-draw-file.js:
window.WebGlDraw = function(points /* point array */)
{
// Draw points here
}
Page1.aspx.cs:
publicstringGetSerializedServerVariable()
{
new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ServerVariable);
}
Page1.aspx:
<html><header><scriptsrc="webgl-draw-file.js"/><scripttype=text/javascript>window.WebGlDraw(<%=this.GetSerializedServerVariable()%>);
</script></header><body>
...
</body></html>
To understand a better what values are passed to the JS function, take a look at a page source using your browser. You should see a JSON representation of your array instead of <%=Page.GetSerializedServerVariable()%>
scriptlet.
It should look something like this:
<html><header><scriptsrc="webgl-draw-file.js"/><scripttype=text/javascript>window.WebGlDraw([{x:1, y:2}, {x:1, y:2}, {x:1, y:2}, {x:1, y:2}]);
</script></header><body>
...
</body></html>
Solution 2:
can u serialize the data like this:
<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var doublearr = <%= serializer.Serialize(ServerVariable) %>;
Post a Comment for "Passing Variable Values From C# To Javascript"