Birdman
Birdman

Reputation: 5414

Accessing code-behind variables from page code

I have the following two pages:

  1. Default.aspx
  2. Default.aspx.cs

How do I access variables in the code-behind file (Default.aspx.cs) from my embedded code in (Default.aspx) with the <% %> syntax?

Upvotes: 8

Views: 8893

Answers (3)

David
David

Reputation: 218808

Any public or protected (but not private, the "page" itself inherits from the code-behind Page class) class-level member can be accessed in this way. For example, if your code-behind class has a property:

protected string SomeValue { get; set; }

Then in your aspx code you can refer to it:

<% =SomeValue %>

Upvotes: 16

Mubarek
Mubarek

Reputation: 2689

If you don't specify the access modifier for the variable the default is private and hence you cannot access it inside your page. It works for public, protected and friend. I prefer to use protected variables than public ones.

Upvotes: 0

Greg B
Greg B

Reputation: 14888

Simply reference them as if they are part of the current class.

<%= this.Foo %>

Upvotes: 0

Related Questions