【发布时间】:2017-01-12 19:11:53
【问题描述】:
我正在使用带有 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 更改为公共字符串而不是公共静态字符串,但是现在我得到了这个浏览器错误:未知的 web 方法,我不知道这个问题是否是因为我的 ajax 代码中的错误 url 引用,这是我的 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 位于我的根文件夹中,不在根文件夹中的子文件夹等。
如何解决我的问题?或者我可以改变什么来使它工作。
【问题讨论】: