재우니의 블로그




How to Pass Values from CodeBehind to JavaScript?

 

Using HiddenField

Using a HiddenField control is one of the very common options which we can use to send some values from server to clientside. You can do this, by declaring a HTML INPUT control with type as hidden and setting runat attribute to server. Another way is to drag and drop a HiddenField control from visual studio toolbox.

ASPX

  <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).ready(function() {

         alert($("#hfServerValue").val());

         });

     </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:HiddenField ID="hfServerValue" runat="server" />

 

Codebehind

  protected void Page_Load(object sender, EventArgs e)

    {

        hfServerValue.Value = "From Server";

    }

 

Setting a Javascript Variable using <% %> blocks

We can embed the C# code using the <% %> construct in ASPX page. To do this, declare a public variable and assign it to a javascript variable through <% %> construct. Refer below,

 

ASPX

 <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).ready(function() {           

             var servervalue = '<%=FromServer %>';

             alert(servervalue);

         });

     </script>

</head>

<body>

    <form id="form1" runat="server">

 

Codebehind

 public string FromServer;

    protected void Page_Load(object sender, EventArgs e)

    {      

        FromServer = "From Server";

    }

 

Declaring JavaScript Variable from CodeBehind

This is one another way where we can declare a javascript variable by constructing the javascript from codebehind and assign a value. Refer the below code,

ASPX

<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).ready(function() {           

             alert(JSVar);

         });

</script>

 

CodeBehind

public string FromServer;

    protected void Page_Load(object sender, EventArgs e)

    {        

        FromServer = "From Server";

 

        StringBuilder strScript = new StringBuilder();

        strScript.Append("<script type=\"text/javascript\">");

        strScript.Append("var JSVar='");

        strScript.Append(FromServer);

        strScript.Append("';");       

        strScript.Append("</script>");

 

        ClientScriptManager script = Page.ClientScript;

 

        if (!script.IsClientScriptBlockRegistered(this.GetType(), "Var"))

        {

            script.RegisterClientScriptBlock(this.GetType(), "Var", strScript.ToString());

        }

 

    }

 

Once executed, the above code will emit the javascript variable with a value to the output HTML(similar to below).

 

<body>

    <form name="form1" method="post" action="CBTOJS.aspx" id="form1">

<div>

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNTM4NjU4ODE1ZGQElWxBiEc2w9QhtjJyaVl59BWiPw==" />

</div>

<script type="text/javascript">var JSVar='From Server';</script>

 

Using Expando Attribute

Another way of sending some information or data from server to client side is by adding a custom attribute to a control through AttributeCollection of that control. For example,

 

  btnSave.Attributes.Add("flag", "From ASP.Net!");

 

The above custom attribute can be accessed in javascript like below,

 

<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">      

$(document).ready(function() {

         alert($('#btnSave').attr("flag"));

});

     </script>

 

The main disadvantage of the above approach is, the HTML generated by the ASP.Net for the above code is not XHTML complaint since flag is not a valid attribute of INPUT control. Below is the HTML generated when we use AttributeCollection.

 

<input type="submit" name="btnSave" value="Save" id="btnSave" flag="From ASP.Net!" />

 

To prevent this, the ClientScriptManager class has a method called RegisterExpandoAttribute() which can be used. This method can be used add a custom attribute a control which can be accessed in clientside by making it XHTML complaint.

 

This method has 2 overloads.

1.      RegisterExpandoAttribute(String controlID, String attribute, String value)  

Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value).

2.      RegisterExpandoAttribute(String, String, String, Boolean)

Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value) and a Boolean value indicating whether to encode the attribute value.

 

  To attach custom property called “LastPostBackTime” to a button control we can use,

 

Page.ClientScript.RegisterExpandoAttribute(btnSave.ClientID, "LastPostbackTime", DateTime.Now.ToString());

 

To Access the attribute in JavaScript,

  alert(document.getElementById("btnSave").LastPostbackTime);

 

 Or you can use the above jquery script.

 

When we use RegisterExpandoAttribute method, the custom attribute will be segregated in a separate javascript making the control clean and XHTML complaint. Refer the below output,

<script type="text/javascript">

<!--

var btnSave = document.all ? document.all["btnSave"] : document.getElementById("btnSave");

btnSave.LastPostbackTime = "19/03/2009 8:47:24 PM";

// -->

</script>





 How to Pass Values from JavaScript to CodeBehind?

 

Using HiddenField Control

Again using a HiddenField control is one of the most common ways of sending client data to ASP.Net. The below code does that,

ASPX

<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).ready(function() {            

         $("hfServerValue").val("From ClientSide!");

         });

     </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:HiddenField ID="hfServerValue" runat="server" />

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)

    {      

        Response.Write(hfServerValue.Value);

    }

 

You can also use a HTML INPUT control by setting runat="server".

 

Using __doPostBack() method

One another way to pass values from javascript to ASP.Net codebehind is to use the __EventArgument in __doPostBack() method. To know more about this method and to use it you can refer Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net

 

If you have a control that emits __doPostBack() method (or you will have to emit it through code, refer above article) you can use __EventArgument to pass values from a javascript to codebehind. Refer the below code,

ASPX

 <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

     <script type="text/javascript">

         $(document).ready(function() {

             $("#btnSave").click(function() {

                 __doPostBack("lbSave","From Javascript!");

 

             });

 

         });

        

     </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <input id="btnSave" type="button" value="Save" />

    <asp:LinkButton ID="lbSave" runat="server" onclick="Save_Click">lbSave</asp:LinkButton>

 

CodeBehind

protected void Save_Click(object sender, EventArgs e)

    {

        Response.Write(Request["__EVENTARGUMENT"]);

    }

   

Using Ajax Methods

This is another way where we can make an Ajax call to server whenever we need the server value in javascript/jquery. When you use ASP.Net AJAX then you can use PageMethods for this. Read the below code snippet which demonstrates it with an example.

Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods

 

Also, there are numerous article posted on codedigest on making Ajax calls using jquery. Refer here.