Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an ASP.NET server side method via jQuery

I'm trying to call a server side method from client side via jQuery. My code is as follows:

Server side:

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

Client side:

$("#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; }); 

I've added a break point on the server side SendMessage method, but it's never hitting it, but when I run the code the jQuery success method is called. What could be causing this?`

like image 424
Fermin Avatar asked May 20 '09 08:05

Fermin


People also ask

Can jQuery be used on server side?

No it is not possible to run jQuery on the serverside, as jQuery runs in the users web browser (inside the javascript interpreter) .

Can we call C# code behind using jQuery?

Can we call C# code behind using jQuery? we can but we need to specify the backend method as static . Yes,But it having some prerequisiteC# method mark as webmethod.


2 Answers

To call ASP.NET AJAX "ScriptServices" and page methods, you need to use the full $.ajax() syntax:

$.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.   } }); 

See this post for details on why that's necessary: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Edit: The extension doesn't change to .asmx but remains .aspx.

like image 148
Dave Ward Avatar answered Oct 13 '22 06:10

Dave Ward


It looks like you're trying to make use of a page method.

Take a look here Page Methods in ASP.NET Ajax for help

like image 26
Stephen Newman Avatar answered Oct 13 '22 07:10

Stephen Newman