-1

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.

JoJo
  • 4,643
  • 9
  • 42
  • 65
  • 1
    inside static method you can't access to object, see more on [msdn](https://msdn.microsoft.com/en-us/library/79b3xss3.aspx) – Grundy Jun 16 '15 at 18:09

2 Answers2

3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks. I am running a bit out of idea as I would like to avoid a .net postback was well. – JoJo Jun 16 '15 at 18:16
  • 1
    Well we can't really tell what you're attempting to achieve here, but you'll probably need to provide the web method with *some* context, if it's going to persist a change, for example. The first thing to do is make sure you understand the problem - if you're very new to C#, I'd actually recommend putting ASP.NET down for the moment and learning the basics of the language via console apps. – Jon Skeet Jun 16 '15 at 18:20
1

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

Marc Cals
  • 2,963
  • 4
  • 30
  • 48