2009-07-24 13 views
10

Come si fa a chiamare un metodo su una pagina Web Form ASP.NET utilizzando il metodo getJSON su jQuery?Utilizzo del metodo getJSON di jQuery con un Web Form ASP.NET

L'obiettivo è questo:

  1. utente fa clic su un elemento della lista
  2. Il valore viene inviato al server
  3. Server risponde con la lista relativa delle cose, formattata utilizzando JSON
  4. Popola secondaria casella

Non voglio utilizzare un UpdatePanel, l'ho fatto centinaia di volte utilizzando il framework MVC di ASP.NET, ma non riesco a capirlo usando Web Forms!

Finora, posso fare tutto, incluso chiamare il server, semplicemente non chiama il metodo giusto.

Grazie,
Kieron

Alcuni codice:

jQuery(document).ready(function() { 
    jQuery("#<%= AreaListBox.ClientID %>").click(function() { 
     updateRegions(jQuery(this).val()); 
    }); 
}); 

function updateRegions(areaId) { 
    jQuery.getJSON('/Locations.aspx/GetRegions', 
     { areaId: areaId }, 
     function (data, textStatus) { 
      debugger; 
     }); 
} 

risposta

24

Ecco un esempio minimalista che dovrebbe auspicabilmente iniziare:

<%@ Page Language="C#" %> 
<%@ Import Namespace="System.Web.Services" %> 

<script runat="server"> 
    [WebMethod] 
    public static string GetRegions(int areaId) 
    { 
     return "Foo " + areaId; 
    } 
</script> 

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>jQuery and page methods</title> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
</head> 
<body> 
    <script type="text/javascript"> 
    $(function() { 
     var areaId = 42; 
     $.ajax({ 
      type: "POST", 
      url: "Default.aspx/GetRegions", 
      data: "{areaId:" + areaId + "}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(data) { 
       alert(data.d); 
      } 
     }); 
    }); 
    </script> 
</body> 
</html> 
0

ho ottimizzato il codice un po '. Ho aggiunto l'output lato server di ClientID al metodo updateRegions per passarlo. E ho cambiato il metodo getJSON per passare l'url con un parametro stringa di query (invece di dati separati) e la funzione di richiamata.

jQuery(document).ready(function() { 
    jQuery("#<%= AreaListBox.ClientID %>").click(function() { 
     updateRegions(<%= AreaListBox.ClientID %>); 
    }); 
}); 

function updateRegions(areaId) { 
    jQuery("h2").html("AreaId:" + areaId); 

    jQuery.getJSON("/Locations.aspx/GetRegions?" + areaId, 
     function (data, textStatus) { 
      debugger; 
     }); 
} 

Fammi sapere se funziona!

0

È inoltre possibile utilizzare un getJSON, ma si dovrebbe modificare il WebMethod in quel caso. Dovresti decorarlo con:

[WebMethod(EnableSession = true)]  
[ScriptMethod(UseHttpGet =false, ResponseFormat = ResponseFormat.Json)] 

Fare un get potrebbe non essere quello che desideri.

Problemi correlati