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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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 %>';
alert(JavaVar1+"---"+JavaVar2+"---"+JavaVar3);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<%-- 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 />
</div>
</form>
</body>
</html>
// 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
{
get
{
return "Property Variable";
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Bind data from code-behind to ASPX server controls
Page.DataBind();
}
}
</script>