简体   繁体   English

为什么在后面的代码中创建的对象在aspx页面中不可用?

[英]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. 当我们在后面的代码中创建一个对象(“.aspx.cs”)时,为什么它在aspx页面中不可用。

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". 例如,如果我有一个类(存在于另一个.cs文件而不在后面的代码中)并且在该类中我声明了一个属性,那么就说“名称”。

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. 现在,当我创建一个对象时,让我们在后面的代码(“.aspx.cs”)中说“obj”,并在范围内使用范围。

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. 使用此对象“obj”我可以访问该属性。 Then why can't I use the same object "obj" to get the property in the aspx page in this manner, 那么为什么我不能使用相同的对象“obj”以这种方式获取aspx页面中的属性,

<%= 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 现在当我创建一个对象时,让我们在后面的代码中说“obj”(“。aspx.cs”),使用这个对象“obj”我可以访问该属性

It's not clear how exactly you created this obj instance. 目前尚不清楚你是如何创建这个obj实例的。 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. 如果它是后面代码中方法中的某个局部变量,很明显该变量的范围是方法本身,因此您无法在ASPX页面中访问它。

In the ASPX page you can only access members of the current WebForm which are defined in the code behind. 在ASPX页面中,您只能访问后面代码中定义的当前WebForm的成员。 So this obj must be instantiated somewhere. 所以这个obj必须在某个地方实例化。 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: 然后在ASPX页面中,您可以访问它:

<%= MyObj.Name %>

Let's take another example which allows you to initialize the property for example in the Page_Load event: 让我们再举一个例子,它允许你初始化属性,例如在Page_Load事件中:

protected SomeType MyObj { get; private set; }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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