Search code examples
c#asp.netascx

How can I call non-static value in ascx file? (.net framework 1.1)


I got a class like this:

namespace MYSCommon
{
   [Serializable]
   public class Cart
   {        

    // Methods
    public Cart(){
         //Code skip
    }

    public double Value{
        //Code skip
    }
   }
}

I use this method to call in the aspx, it got an error:

The code: <%= MYSCommon.Cart.Value %>

The error: Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property 'MYSCommon.Cart.Value'

But I got another like this:

namespace MYSCommon
{
    public class Constant
    {
        // Fields
        public static string staticValue = "Something";
    }
}

and called it via: <%= MYSCommon.Constant.staticValue %>, which is success. How can I solve it? Thanks.


Solution

  • You can't access instance variable without the class instance. In the code behind of ascx you may create a public instance of type Cart like:

    Code behind of ascx:

    public MYSCommon.Cart myCart = new MYSCommon.Cart();
    

    later you can access it like:

    in ascx:

    <span> <%= myCart.Value %> </span>
    

    Just make sure that myCart is declared as public and at Page level.