Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing code behind functions from WebMethod

Tags:

asp.net

I have a code behind page that has several method; one of them is a page method.

[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
    LoadCallHistory(TheNewDate.Date);
}

protected void LoadCallHistory(DateTime TheDate)
{ bunch of stuff }

The method LoadCallHistory works fine when the page loads and I can call it from other methods inside the page. However, in the web method part, it gets underlined in red with the error "an object reference is required for the non-static field".

How do you access functions from the page method part of the code?

Thanks.

like image 371
frenchie Avatar asked Apr 25 '26 17:04

frenchie


1 Answers

You cannot call a non-static method from a static context without having an instance of the class. Either remove static from ResetDate or make LoadCallHistory static.

However, if you remove static from ResetDate you must have an instance of it to use that method. Another approach is to create an instance of the class inside ResetDate and use that instance to call LoadCallHistory, something like this:

[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
    var callHistoryHandler = new Pages_CallHistory();
    callHistoryHandler.LoadCallHistory(TheNewDate.Date);
}

The error message indicates that ResetDate has the keyword static and LoadCallHistory does not. When using static either both of the methods needs to be static or the called method needs to be static, the caller cannot be static if the called method is not.

To quote MSDN on "Static Classes and Static Class Members"

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

like image 196
Filip Ekberg Avatar answered May 01 '26 05:05

Filip Ekberg