Llamando a un ASP.NET método del lado del servidor a través de jQuery


Estoy tratando de llamar a un método del lado del servidor desde el lado del cliente a través de jQuery. Mi código es el siguiente:

Lado del servidor:

    using System.Web.Services;
    [WebMethod()]
    //[ScriptMethod()]
    public static void SendMessage(string subject, string message, string messageId, string pupilId)
    {
        //Send message
    }

Lado del cliente:

$("#btnSendMessage").live("click", function(){
  var subject = $("#tbSubject").val();
  var message = $("#tbMessage").val();
  var messageId = $("#hdnMessageId").val();
  var pupilId = $("#hdnPupilId").val();

  $.ajax({
      type: "POST",
      url: "./MessagePopup.aspx/SendMessage",
      data: ("subject=" + subject + "&message=" + message + "&messageId=" + messageId + "&pupilId=" + pupilId),
      error: function(XMLHttpRequest, textStatus, errorThrown){
          alert(textStatus);
      },
      success: function(result){
         alert("success");
      }
   });
   return false;
});

He agregado un punto de interrupción en el método SendMessage del lado del servidor, pero nunca lo golpea, pero cuando corro el código se llama al método jQuery success. ¿Qué podría estar causando esto?`

Author: Peter Mortensen, 2009-05-20

5 answers

Para llamar ASP.NET AJAX "ScriptServices" y métodos de página, necesita usar el full completo.sintaxis:

$.ajax({
  type: "POST",
  url: "MessagePopup.aspx/SendMessage",
  data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

Vea este post para detalles sobre por qué es necesario: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods /

Editar: La extensión no cambia a .asmx pero permanece .aspx.

 37
Author: Dave Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-19 18:10:52

Parece que estás tratando de hacer uso de un método de página.

Echa un vistazo aquí Métodos de página en ASP.NET Ajax para ayuda

 9
Author: Stephen Newman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-20 10:11:50

Debe usar el servicio web en lugar de la página web regular de aspx. Web pages no tiene soporte para llamar a métodos web, creo que su solicitud jQuery carga la página HTML en su lugar. Te sugiero dos cosas:

  1. Use Fiddler2 (con IE) o HttpFox (con Firefox) para depurar solicitudes y respuestas AJAX en el lado del cliente.
  2. Utilice el servicio web WCF en el lado del servidor. en este caso puede usar SvcConfigEditor y SvcTraceViewer para configurar y depurar métodos web en el servidor lado.
 2
Author: Artem Koshelev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-20 10:09:20
$.ajax({  
        type: "POST",  
        url: "MessagePopup.aspx/SendMessage",  
        data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",  
        async: true,  
        cache: false,  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",  
        success: function() {},  
        error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); }  
     });

Si esto no funciona...y da "Error de sintaxis: error de sintaxis"...a continuación, añadir esto

<httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>

Entre </compilation> y </system.web> en tu Web.Archivo de configuración.

Espero que esto ayude a alguien porque me llevó un tiempo calcular que al lado de la función jquery tengo que agregar eso en la Web.Config.

 2
Author: Frank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-27 23:03:27

Aquí está el código que podría funcionar en su situación.

<script type="text/javascript">
    $(document).ready(function () {

        // Add the page method call as an onclick handler for the button.
        $("#btnSubmit").click(function () {

            //get the string from the textbox
            $.ajax({

                type: "POST",
                url: "testSearch.aspx/GetMyShippingDate",
                contentType: "application/json; charset=utf-8",
                data: "{'tracking_num': '" + $("#txtTrackingNumber").val() + "'}",  
                dataType: "json",
                success: function (date) {

                    // Replace the div's content with the page method's return.
                    Success(date);

                },
                error: Failed
            });
        });
    });

     function Success(result) {  
          $("#ParcelShippingDate").html(result.d);
      }  
      function Failed(result) {  
          alert(result.status + " " + result.statusText);  
      }  

Hay un ejemplo que siempre ha funcionado para mí.

Aquí está el artículo completo http://www.webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-net-web-page.aspx

Funciona bien para aquellos que quieren una forma directa de usar jquery asp.net método call back

 1
Author: Junimation,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 23:17:00