Monday, March 23, 2009

How to return values from JavaScript function to the C# page load

Add the JavaScript function just below the HTML <title> tag. This function should have __doPostBack to return value.
   1:     <script language="javascript">
   2:          function RetVal()
   3:          {
   4:              var testVar = 'abc'
   5:              __doPostBack('Test',testVar);
   6:          }
   7:      </script>

Add a label to display the values from JavaScript function.
Add a text box to page and set the AutoPostBack property to true. One control with AutoPostBack property set to true is required in the page to get the value from JavaScript function using __doPostBack.
In Page_Load write the following code.
   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:    if (IsPostBack)
   4:    {
   5:      string arg = Request.Form["__EVENTTARGET"];
   6:      string val = Request.Form["__EVENTARGUMENT"];
   7:      if (arg == "Test")
   8:      {
   9:       Label1.Text = val;
  10:      }
  11:    }
  12:     else
  13:     {
  14:      string script;
  15:      script = @"<SCRIPT language='javascript'> RetVal
           ();" + "</SCRIPT>";
  16:      Page.RegisterStartupScript("Test", script);
  17:     }
  18:    }

Page.RegisterStartupScript: Allows ASP.NET server controls to emit client-side script blocks in the Page, now this method is obsolete, in ASP.NET 2.0 it gives you an error - or more correctly warnings telling you that both functions are obsolete.
'System.Web.UI.Page.IsStartupScriptRegistered(string)' is obsolete: 'The recommended alternative is ClientScript.IsStartupScriptRegistered(string key).
"The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control."
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server
Execute the code and see the result…