How to pass the variable value from codebehind to javascript

In this article i am going to show you how to pass the variable value from codebehind to javascript. It is quite easy and handy.

I have declared a protected type string variable Variable_codebehind in asp.net codebehind, assign a value to that variable on page load .
Code:

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

public partial class _Default : System.Web.UI.Page
{
    protected string Variable_codebehind;
    protected void Page_Load(object sender, EventArgs e)
    {
        Variable_codebehind = "Ashish Blog";
    }
}

Now, we going to diaplay this variable Variable_codebehind into html page using javascript.
Code:

<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server"> 
<title>Ashish's Blog</title>
  <script type="text/javascript">
         ////Getting variable from asp.net code behind  
          alert("<%=Variable_codebehind %>");
   </script>
</head>
<body>
<form id="form1" runat="server">  
<div>  
</div>  
</form>  
</body>
</html>

Thanks.

2 responses to “How to pass the variable value from codebehind to javascript”

Leave a Reply