Home > OS >  an object reference is required for the non-static field method or property 'page.request'
an object reference is required for the non-static field method or property 'page.request'

Time:04-19

I am at the initial stage of learning ASP.NET Webforms as a beginner and I am working with this block of code where I need to invoke Request.QueryString from a static method. But I am not being able to do that and instead it throws a compilation error

This is my block of code

[System.Web.Services.WebMethod]
    public static string GetProductImgList(string ProductCode)
    {
        try
        {
            string ProductId = Request.QueryString["ID"].ToString(); //error
            string BatchId = Request.QueryString["Batch"].ToString();//error
            string UserId = Request.QueryString["UID"].ToString();//error

            dalOnlineShop objdalOnlineShop = new dalOnlineShop();
            DataTable dt = objdalOnlineShop.GetProductAllImgs(ProductCode);
            string ImgNames = "";
            for (int i = 0; i < dt.Rows.Count; i  )
            {
                if (dt.Rows.Count == i   1)
                {
                    ImgNames  = dt.Rows[i]["SmallImgPath"].ToString()   ",";
                    ImgNames  = dt.Rows[i]["ImgPath"].ToString();
                }
                else
                {
                    ImgNames  = dt.Rows[i]["SmallImgPath"].ToString()   ",";
                    ImgNames  = dt.Rows[i]["ImgPath"].ToString()   ",";
                }
            }
            return ImgNames;
        }
        catch (Exception ex) { }
        return "";
    }

CodePudding user response:

Your issue here is that you made this method static. Static means that it's not tied to a specific instance. The Request property that this code is referring to is an instance property. This means that this property (can) have a different value for each instance.

ASP.NET will create a new instance of this class for each request that enters, this will make it easier to share information like the Request, Response, Context, ... for a specific request, so you have to think less about tying this all together.

  • Related