How to pass value from server side to client side in asp net

In this article, I will show you how to access C# (server-side ) variable in javascript. The idea here is to prepare the javascript variable and add it to RegisterClientScriptBlock

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ServerSideArrayOnClient.aspx.cs" Inherits="ServerSideArrayOnClient" %>

<!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 id="Head1" runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="Form1" runat="server">
   <div>
       <asp:TextBox ID="Message" runat="server"></asp:TextBox>
       <input type="button" value="get value" onclick="DoClick()" />
   </div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class ServerSideArrayOnClient : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String arrName = "MyArray";
        String arrValue = "11, 3, 7";
        ClientScriptManager cs = Page.ClientScript;
        cs.RegisterArrayDeclaration(arrName, arrValue);
        StringBuilder cstext = new StringBuilder();
        cstext.Append("<script type=\"text/javascript\"> function DoClick() {");
        cstext.Append("document.getElementById('"+Message.ClientID+"').value=");
        cstext.Append("(parseInt(" + arrName + "[1]));}</");

        cstext.Append("script>");
        String csname = "ConcatScript";
        Type cstype = typeof(Page);
        cs.RegisterClientScriptBlock(cstype, csname, cstext.ToString(), false);
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru