我正在尝试使用jquery ajax在aspx页面中调用webmethod。 ajax代码是callind页面,但是我不能进入方法,尽管在ajax Post请求之后已经加入了Page_Load。我在很多方面尝试过,但我做不到。
我希望你能帮助我,我会发疯。
protected void Page_Load(object sender, EventArgs e)
{
string nombre = Request.QueryString["nombre"];
if (!IsPostBack)
{
this.CargarDatosIniciales();
}
}
[WebMethod(enableSession:true)]
[ScriptMethod()]
public static void GuardarDatosFamilia(string nombre, string tipoDoc)
{
string nombrePersona = nombre;
string tipoDocumento = tipoDoc;
}
$.ajax({
type: "POST",
url: "FRM_Caracterizacion.aspx/GuardarDatosFamilia", //Direccion del servicio web segido de /Nombre del metodo a llamar
beforeSend: function () { alert('I am sending'); },
data: "{'nombre':'"+ nombre+"','tipoDoc':'"+ tipoDoc"'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
更新:
这是我在Firebug中得到的:
POST http://localhost:51620/FRM_Caracterizacion.aspx/GuardarDatosFamilia 200 OK 3.22s
Parámetros application/x-www-form-urlencoded
nombre Jhon Fredy
tipoDoc 1
Fuente
nombre=Jhon+Fredy&tipoDoc=1
更新2:
解
我为我的具体问题所做的是:
$.ajax({
type: "POST",
url: "FRM_Caracterizacion.aspx", //Direccion del servicio web segido de /Nombre del metodo a llamar
beforeSend: function () { alert('I am sending'); },
data: { metodo: 'AgregarDatosFamilia',
nombre:nombre,
tipoDoc:tipoDoc
},
dataType: "json" //Esto quiere decir que los datos nos llegaran como un objeto json
});
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Form["metodo"] == "AgregarDatosFamilia")
{
this.GuardarDatosFamilia();
}
this.CargarDatosIniciales();
}
}
public void GuardarDatosFamilia()
{
string nombre = Request.Form["nombre"].ToString(),
string tipoDoc = Request.Form["tipoDoc"].ToString()
}
谢谢大家,我很感激建议!
答案 0 :(得分:2)
确保您在客户端正确调用此功能
$.ajax({
type: "POST",
url: "FRM_Caracterizacion.aspx/GuardarDatosFamilia", //Direccion del servicio web segido de /Nombre del metodo a llamar
beforeSend: function () { alert('I am sending'); },
data: "{'nombre':'"+ nombre+"','tipoDoc':'"+ tipoDoc"'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
然后在浏览器中点击F12并观察流量 - 您将看到正在调用web方法,但您没有返回任何内容,
[WebMethod(enableSession:true)]
[ScriptMethod()] //this can't be void - change to String
public static String GuardarDatosFamilia(string nombre, string tipoDoc)
{
string nombrePersona = nombre;
string tipoDocumento = tipoDoc;
return "successful ajax";
}
尝试进行测试 - 如果你试图访问在Page_Load中声明的字符串nombre - 这在静态方法中是不可能的,那么你将有权访问的唯一数据是传递给webmethod的内容
我发表评论说要将其从虚空中更改 - 它实际上可能是无效的 - 但是如果您想要执行某些操作(通常是使用数据库) - 即使这样,它的良好做法是返回字符串以让客户知道如果成功与否
答案 1 :(得分:1)
为webmethod创建不同的网络服务,阅读更多Consuming-Webservice-using-JQuery-ASP-NET-Applicat和calling webservice