How to pass value from server page to client function in asp.net

In my application, I need to pass a string value from the server side (.aspx.cs) to a function on the client side (.aspx).

Can someone help me by providing ideas and sample code if possible?

+6
source share
3 answers

If you mean that you need to pass the value to the javascript function, then you can do something like this ...

In the .aspx file:

<script language="javascript" type="text/javascript"> var stringValue = '<%=GetStringValue();%>'; // For example: alert(stringValue); </sctipt> 

In the .aspx.cs file:

 private string GetStringValue() { return "A string value"; } 

Then a javascript message will be shown with the message "String value" when the page loads

+9
source share

You can generate a server-side script and paste the value into it:

 StringBuilder sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\""); sb.Append("var someFunc = function(){"); sb.AppendFormat("alert('{0}');", importantServerSideValue); sb.Append("};"); sb.Append("</script>"); Page.ClientScript.RegisterClientScriptBlock("genScript", sb.ToString()); 

Or put the value in a hidden form element on the page and access it from the client side Javascript.

 <!-- In the Markup --> <asp:HtmlInputHidden id="hiddenField" runat="server" /> // And in the code-behind hiddenField.Value = importantServerSideValue; 
+1
source share

When I had to pass a variable value from PHP to JS, I used php to echo from js with the variable set to the value of the php variable. eg.

 //php code echo 'var number = ' . $variable . ';'; 
0
source share

All Articles