static void c# webmethod can't reference user control?

400 views Asked by At

I have a WebMethod where I just want to flip a property to true.

I am putting it in the code-behind of a .aspx page using C#.

public partial class Data : Base
{ 
    protected void Page_Load(object sender, EventArgs e)
    {
        this.bgc1.BGEnabled = false;
    }

    [WebMethod(EnableSession = true)]
    public static void EnableBellows()
    {
        this.bgc1.BGEnabled = true;            
    }
}

I declare the property in the .ascx.cs file:

private bool _enabled = true;

public bool BGEnabled
{
    get { return _enabled; }
    set { _enabled = value; }
}

Lastly I call the WebMethod with a jQuery Ajax post.

I am getting the error that this is not valid in a static property. This error is only in the WebMethod but not in the Page_Load.

My goal is to flip BGEnabled to true. If my approach is incorrect, what will I need to do differently? I need to be able to do it from an ajax post.

2

There are 2 answers

2
Jon Skeet On BEST ANSWER

I am getting the error that this is not valid in a static property.

Indeed. In fact, in this case, it's a static method.

A static member is one which is associated with the type, rather than with any instance of the type - so here, we could call EnableBellows directly as:

Data.EnableBellows();

... without creating any instance of Data. As this is meant to refer to "the instance of the object that the method was called on", it's meaningless in a static member.

You need to think about where your data would come from, and what you'd do with the modified data. Bear in mind that the web method is not called as part of loading the page, so it doesn't have access to any of the controls on the page, etc.

Basically, I suspect you need to revisit the whole notion of web methods and ASP.NET pages.

0
Marc Cals On

Inside static method you can only access static methods/objects or instancesdeclared inside the scope of the static method