非静态字段方法或属性

时间:2017-01-12 19:11:54

标签: c# asp.net webmethod

我使用带有WebMethod的C#aspx Web表单但是我在尝试使用公共方法调用类时遇到问题,我收到此错误消息:

  

非静态字段方法或属性需要对象引用。

以下是我的代码示例。

DB_Class

public int Cuenta(User us, int opcion)
{
    string sql = "";
    int res = 0;

    switch (opcion)
    {
        //Insert
        case 1:
            sql = "query...";
            break;
            //Update
        case 2:
            sql = "";
            break;
            //Delete
        case 3:
            sql = "";
            break;
    }
    //More code, using executenonquery etc. there is no problem with that.
    return res;
}

ASPX,Web方法代码

db_Class conn = new db_Class();

[WebMethod]
public static string RegistrarCuenta(int id, string usuario, string nombre, string apellido, string email, string password, string fechaNacimiento, int tipo, int op)
{
    string respuesta = "Ha Ocurrido Un error.";

    try
    {
        User us = new User(id, usuario, nombre, apellido, email, password, fechaNacimiento, tipo);
        //I get the error here.
        int resp = conn.Cuenta(us, op);

        if (resp > 0)
            respuesta = "Operacion Realizada Correctamente.";
    }
    catch (Exception ex)
    {
        respuesta = "Ha Ocurrido un error: " + ex.Message;
    }

    return respuesta;
}

我在这里寻找解决方案,但我没有发现任何类似我的问题(尝试在另一个类中调用方法)。此外,我试图将我的webmethod更改为公共字符串intead的公共静态字符串,但现在我得到此浏览器错误:未知的Web方法,我不知道这个问题是否是我的ajax代码中的错误url引用,这里是我的< strong> ajax 代码:

 $.ajax({
            type: 'POST',
            url: 'registrar.aspx/RegistrarCuenta',
            data: '{' +
                '"id":' + id +
                ',"usuario":"' + user +
                '","nombre":"' + nombre +
                '","apellido":"' + apellido +
                '","email":"' + email +
                '","password":"' + password +
                '","fechaNacimiento":"' + date +
                '","tipo":' + 2 +
                ',"op":' + 1 + '}',
            dataType: "json",               // Tipo de datos que se envian
            contentType: "application/json",            // Tipo de datos qu se envian
            timeout: 60000,             // Tiempo de espera para que occura un error de timeout
            error: function (xhr) {     // Evento que se dispara al ocurrir un error en la peticion
                swal("Algo a salido mal...", "Error!", "error")
            },
            success: function (data) {   // Evento que se dispara cuando se realiza correctamente
                swal(data.d, "", "success");
            }
        });

PD。 registrar.aspx位于我的根文件夹中,根目录中没有子文件夹等。

如何解决我的问题?或者我可以改变什么才能使它发挥作用。

2 个答案:

答案 0 :(得分:6)

conn是一个实例成员,无法在静态上下文中访问它,因为没有实例可供使用。

更重要的是,使用共享连接对象(静态上下文中的尤其是)通常是一个非常糟糕的主意。只需在需要的地方/何时创建连接对象:

db_Class conn = new db_Class();
int resp = conn.Cuenta(us, op);

您可以(并且可能应该)删除类级conn成员并保持连接范围非常小。如果它实现IDisposable,您还应该利用它:

int resp = 0;
using (db_Class conn = new db_Class())
{
    resp = conn.Cuenta(us, op);
}

答案 1 :(得分:0)

在C#或Java中,

您无法在静态方法中访问非静态成员(变量或函数)。您可以将它们声明为静态或在Web方法中初始化局部变量,如@David所暗示的那样。

也请查看此链接 https://msdn.microsoft.com/en-us/library/98f28cdx.aspx