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"

<html xmlns="" >
<head id="Head1" runat="server">
   <title>Untitled Page</title>
   <form id="Form1" runat="server">
       <asp:TextBox ID="Message" runat="server"></asp:TextBox>
       <input type="button" value="get value" onclick="DoClick()" />

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("(parseInt(" + arrName + "[1]));}</");

        String csname = "ConcatScript";
        Type cstype = typeof(Page);
        cs.RegisterClientScriptBlock(cstype, csname, cstext.ToString(), false);
Next Post Previous Post
No Comment
Add Comment
comment url