通过 jQuery 调用 ASP.NET 服务器端方法 [英] Calling an ASP.NET server side method via jQuery

查看:26
本文介绍了通过 jQuery 调用 ASP.NET 服务器端方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 jQuery 从客户端调用服务器端方法.我的代码如下:

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

服务器端:

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

客户端:

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

我在服务器端的 SendMessage 方法上添加了一个断点,但它从来没有命中它,但是当我运行代码时,jQuery 成功方法被调用.什么可能导致这种情况?`

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?`

推荐答案

要调用 ASP.NET AJAXScriptServices"和页面方法,需要使用完整的 $.ajax() 语法:

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

有关为什么需要这样做的详细信息,请参阅此帖子:http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

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/

扩展名不会更改为 .asmx,但仍为 .aspx.

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

这篇关于通过 jQuery 调用 ASP.NET 服务器端方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆