Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a variable in code behind to aspx page

Tags:

c#

asp.net

i know i have seen this but cant recall the correct way of doing it... basically i have a string variable called "string clients" in my .cs file.. but i wasn't to be able to pass it to my aspx page something like

<%=clients%>   

please correct me, i do not recall or not sure how to do this. (new to c#) and when i googled it.. it was not clear.. or not many of these out there.. searched as

"asp.net c# <%= %> not consistent results.. maybe because i do not know how to call these..

like image 976
user710502 Avatar asked Sep 13 '11 18:09

user710502


People also ask

How do you relate an ASPX page with its code behind page?

aspx page must specify to inherit from the code-behind base class. To do this, use the Inherits attribute for the @ Page directive. The . aspx page inherits from the code-behind class, and the code-behind class inherits from the Page class.

How do you pass a variable from ASPX CS to ASPX page?

If you need to pass the value from the code-behind to the HTML page, you can use a hidden field for the relay. Then, you can get the value from the HiddenField1 via document. getElementById("HiddenField1").


2 Answers

The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:

 private string clients; public string Clients { get { return clients; } }  

UPDATE: It can also be declared as protected, as stated in the comments below.

Then, to call it on the ASPX side:

<%=Clients%>

Note that this won't work if you place it on a server tag attribute. For example:

<asp:Label runat="server" Text="<%=Clients%>" />

This isn't valid. This is:

<div><%=Clients%></div>

like image 166
Joel A. Villarreal Bertoldi Avatar answered Sep 24 '22 06:09

Joel A. Villarreal Bertoldi


In your code behind file, have a public variable

public partial class _Default : System.Web.UI.Page {     public string clients;      protected void Page_Load(object sender, EventArgs e)     {         // your code that at one points sets the variable         this.clients = "abc";     } } 

now in your design code, just assign that to something, like:

<div>     <p><%= clients %></p> </div> 

or even a javascript variable

<script type="text/javascript">      var clients = '<%= clients %>';  </script> 
like image 36
balexandre Avatar answered Sep 23 '22 06:09

balexandre