Hi,
If we want to pass server variable to JavaScript, we can declare this variable to public and use <% = VariableName%> in JavaScript.
We also can write the Variable to client. For example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public string strVar = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
strVar = "Hello world";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
strVar = "New Variable";
string strScript = "str= '" + strVar + "'";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "script", strScript, true);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
var str = '<%= strVar %>';
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler()
{
alert(str);
}
</script>
<asp:updatepanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<asp:button ID="Button1" runat="server" Text="Show Image" OnClick="Button1_Click" />
</contenttemplate>
</asp:updatepanel>
</div>
</form>
</body>
</html>
I look forward to hearing from you.