We help IT Professionals succeed at work.

Assign the value to a script global variable from the Server side code

HelpSunny asked
   I need to set the value of a global script variable at the server code.
Say for e.g.
1) in test1.js, I have a variable called,
   var setFrmServerCode;
2) How to set its value to "test" from the code behind file, meaning from aspx.cs file
And its setting at the server code shud not  break the existing script file methods
Watch Question

Top Expert 2014

OnSubmit event, you can set the value of an asp:HiddenField with the value of the global variable :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication23._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <script language="javascript" type="text/javascript">
        var setFrmServerCode = "10";
     <form id="Form1" runat="server">
        <asp:HiddenField id="setFrmServerCode" runat="server" />
        <asp:TextBox ID="mytext" runat="server" ></asp:TextBox>
        <input type="submit" value="Submit" />

Open in new window

Top Expert 2014

OnSubmit : http://msdn.microsoft.com/fr-fr/library/system.web.ui.clientscriptmanager.registeronsubmitstatement.aspx

To set our HiddenField, we use : document.getElementById(\"" + setFrmServerCode.ClientID + "\").value = setFrmServerCode;

code behind :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication23
    public partial class _Default : System.Web.UI.Page
        public void Page_Load(Object sender, EventArgs e)
            // Define the name and type of the client script on the page.
            String csname = "OnSubmitScript";
            Type cstype = this.GetType();

            // Get a ClientScriptManager reference from the Page class.
            ClientScriptManager cs = Page.ClientScript;

            // Check to see if the OnSubmit statement is already registered.
            if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
                String cstext = "document.getElementById(\"" + setFrmServerCode.ClientID + "\").value = setFrmServerCode;";
                cs.RegisterOnSubmitStatement(cstype, csname, cstext);

            // for this test page, we set the Texbox with the value of the global variable (The HiddenField value)
            mytext.Text = setFrmServerCode.Value;

Open in new window


I used the hidden variable to do this but when the control moves from server to the client, the
document.getElementID('<%=setFrmServerCode.ClientID'%>).value is coming as undefined.
So, can u suggest an alternative way or Let me know under what scenarios the hiddenvariable value becomes undefined, even though its value is set at the server end.
               One more input, I am setting the value of hidden variable, say for e.g
1)  hidvar at the server end as,
     hidvar.Value = "XYZ"
2) I am collecting its value at the client end in a method called jsCall(url) as,
   function jsCall(url)
     document.getElementID('<%=hidvar.ClientID'%>').value;  //Getting as undefined
3) Calling this script function at the server end by using "Register Client Script" way.

Any help would be highly appreciated....
Top Expert 2014

>document.getElementID('<%=setFrmServerCode.ClientID'%>).value is coming as undefined.

you can't use document.getElementID('<%=setFrmServerCode.ClientID'%>).value on the server side but you must use setFrmServerCode.Value because we set it with the value of the global var setFrmServerCode when submit


Yep, I am using the same way. The Issue is,

At the server end I am setting the value as,
setFrmServerCode.Value = "X";

At the client end I am getting this value as,
var istermExpire = document.getElementID('<%=setFrmServerCode.ClientID'%>).value;

When i run the code, istermExpire is coming as undefined.
Top Expert 2014

do you have a live link ?
One way would be to set the global object. This can cause a timing issue if your global JS variable is not available before this code runs. This is good for an example though.

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _

So a second solution might be to create and set the global variable all at once from code behind. It will then be available for all your JS calls from then on.

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _
        String.Format("var setFrmServerCode={0}","SomeValueAsString")

Another would be to create a function that sets the object and use an event like <body onload> to call the event. This way lets you control the timing and make sure your global variable is available before you try to set it.

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _
        String.Format("function setGlobal(){{ setFrmServerCode= {0};}}","VariableDataAsString")

I've used all of these methods many times in the past with good success. I didn't convert them to C# as I already had these samples laying around. Hopefully you can see what to do and convert them yourself. If necessary I will convert them for you.