Skip to main content

At times, you might need to change properties on server-side controls from a code-behind/partial class, and process data on the client-side. In these cases, accessing code-behind variables in ASPX is the easiest way to get the job done.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Access Code-behind variables in ASPX and Javascript</title>
        <script type="text/javascript">
            //Access Code-Behind Data in Javascript
            var JavaVar1 = '<%=CodeBehindVarPublic %>';
            var JavaVar2 = '<%=CodeBehindVarProtected %>';
            var JavaVar3 = '<%=CodeBehindVarProperty %>';
    <form id="form1" runat="server">
        <%-- Set Properties of server side controls in ASPX using code-behind variables  --%>
        <asp:TextBox ID="TextBox1" runat="server" Width="<%#TextBoxWidth %>"></asp:TextBox>

        <%-- To display Data from code-behind in ASPX controls --%>
        <asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label><br />
        <asp:Label ID="Label2" runat="server" Text="<%#CodeBehindVarProtected %>"></asp:Label><br />
        <asp:Label ID="Label3" runat="server" Text="<%#CodeBehindVarProperty %>"></asp:Label><br />

        <%-- To display Data from code-behind in ASPX --%>
        <%=CodeBehindVarPublic %> <br />
        <%=CodeBehindVarProtected %> <br />
        <%=CodeBehindVarProperty %> <br />

// code behind page...
<script runat="server">
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;

    public partial class Default11 : System.Web.UI.Page
        public int TextBoxWidth = 1000;
        public string CodeBehindVarPublic = "Public Variable";
        protected string CodeBehindVarProtected = "Protected Variable";

        public string CodeBehindVarProperty
                return "Property Variable";

        protected void Page_Load(object sender, EventArgs e)
            // Bind data from code-behind to ASPX server controls