I have a simple question. When we create an object in the code behind(“.aspx.cs”), why is it not available in the aspx page.
For example, if I have a class(present in another .cs file and not in the code behind) and in that class I have a property declared, lets say “Name”.
namespace BLL.SO
{
public class SOPriceList
{
private string _name;
public string Name
{
get { return _name;}
set { _name = value; }
}
}
}
Now when I create an object, lets say “obj” in the code behind(“.aspx.cs”), with scope within the partial class.
namespace Modules.SO
{
public partial class PriceListRecordView : PageBase
{
SOPriceList obj = new SOPriceList();
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Using this object “obj” I can access the property. Then why can’t I use the same object “obj” to get the property in the aspx page in this manner,
<%= obj.Name%>
It’s not clear how exactly you created this
objinstance. If it is some local variable inside a method in the code behind it is obvious that the scope of this variable is the method itself so you cannot access it in the ASPX page.In the ASPX page you can only access members of the current WebForm which are defined in the code behind. So this
objmust be instantiated somewhere. You could for example have a property in your code behind:and then in the ASPX page you could access it:
Let’s take another example which allows you to initialize the property for example in the
Page_Loadevent: