简体   繁体   中英

why an object created in the code behind is not available in the aspx page?

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%>

Now when I create an object, lets say "obj" in the code behind(".aspx.cs"), using this object "obj" I can access the property

It's not clear how exactly you created this obj instance. 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 obj must be instantiated somewhere. You could for example have a property in your code behind:

protected SomeType MyObj
{
    get 
    {
        return ... some instance
    }
}

and then in the ASPX page you could access it:

<%= MyObj.Name %>

Let's take another example which allows you to initialize the property for example in the Page_Load event:

protected SomeType MyObj { get; private set; }

protected void Page_Load(object sender, EventArgs e)
{
    MyObj = new SomeType();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM