← Tutti gli articoli
Consuming ASP.NET Web Services using JQuery
14 February 2011 ·
jQuery · Article ·
592 visite
In this tutorial I will be using JQuery to consume Asp.Net web services in a javascript function to use in the OnClientClick event.
I have a webservice with a function CountFinanziamentoAttachments that returns an int value:
-
namespace MyServices
-
{
-
-
[WebService(Namespace = "http://tempuri.org/" )]
-
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
-
[System.Web.Script.Services.ScriptService]
-
public class GetData : System.Web.Services.WebService
-
{
-
public GetData()
-
{
-
-
-
}
-
-
[WebMethod] // true if you're using Session
-
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
-
public int CountFinanziamentoAttachments( int ID_SpidFinanziamento)
-
{
-
linqContraDataContext linqContra = new linqContraDataContext(ConfigurationManager.ConnectionStrings[ "ContraCS" ].ToString());
-
linqContra.CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings[ "sqlServerTimeout" ]);
-
int ? numeroAttachments = linqContra.Fun_GetSpidFinanziamentoCountAttachments(ID_SpidFinanziamento);
-
-
int n;
-
if (numeroAttachments.HasValue)
-
n = ( int )numeroAttachments;
-
else
-
n=0;
-
-
return n;
-
}
-
-
-
-
-
-
}
-
-
}
- < asp:Content ID = "contentHead" ContentPlaceHolderID = "cphHead" runat = "server" >
- < script src = "jquery/jquery-1.4.1.min.js" type = "text/javascript" > </ script >
- < script src = "Javascript/json2.js" type = "text/javascript" > </ script >
- </ asp:Content >
I consume this webservice function synchronously (async:false) in the following javascript funtion:
- function VerificaNumeroAttach() {
- var vID_SpidFinanziamento=$get( '<%=hf_ID_SpidFinanziamento.ClientID %>' ).value;
- var numero = 0; ///
- $.ajax({
- type: 'POST' ,
- url: '<%= ResolveClientUrl("~/Services/GetData.asmx/CountFinanziamentoAttachments") %>' ,
- contentType: 'application/json; charset=utf-8' ,
- dataType: 'json' ,
- data: "{ID_SpidFinanziamento:" + vID_SpidFinanziamento + "}" ,
- async: false ,
- success: function (msg) {
- numero = getValue(msg);
- },
- error: function () {
- alert( 'Si è verificato un errore nella verifica dei dati del Capo Missione' );
- }
- });
- if ((numero == 0) || (numero == "0" ) ) {
- alert( "E' necessario allegare la dichiarazione del Capo Missione" );
- return false ;
- }
- else {
- return true ;
- }
- }
- < asp:Button ID = "btnSedeApprova" runat = "server" Text = "Approva" OnClientClick = "return VerificaNumeroAttach();" OnClick = "btnApprova_Click" />