Mig*_*res 0 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;
}
Run Code Online (Sandbox Code Playgroud)
ASPX,Webmethod代码
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;
}
Run Code Online (Sandbox Code Playgroud)
我在这里寻找解决方案,但我没有发现任何类似我的问题(尝试在另一个类中调用方法).此外,我尝试将我的webmethod更改为公共字符串intead的公共静态字符串,但现在我得到此浏览器错误:未知的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");
}
});
Run Code Online (Sandbox Code Playgroud)
PD.registrar.aspx位于我的根文件夹中,根目录中没有子文件夹等.
我怎样才能解决我的问题?或者我可以改变什么来使它工作.
conn 是实例成员,无法在静态上下文中访问它,因为没有实例可供使用.
更重要的是,使用共享连接对象(特别是在静态上下文中)通常是一个非常糟糕的主意.只需在需要的地方/何时创建连接对象:
db_Class conn = new db_Class();
int resp = conn.Cuenta(us, op);
Run Code Online (Sandbox Code Playgroud)
您可以(并且可能应该)删除类级别conn成员并保持连接范围非常小.如果它实现了IDisposable,你还应该利用它:
int resp = 0;
using (db_Class conn = new db_Class())
{
resp = conn.Cuenta(us, op);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1620 次 |
| 最近记录: |