使用带有母版页的Web方法

Jam*_*lor 7 asp.net ajax jquery webmethod

我在我的站点中的所有页面上都有一个函数,它位于我的母版页中,我希望它从一些jQuery Ajax方法运行.

我现在有一些像这样的代码

jQuery的

$(document).ready(function() {
  $("#test").click(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetDate",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        $("#test").text(msg.d);
      }
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

主页面中的HTML

<div id="test">Click here for the time.</div>
Run Code Online (Sandbox Code Playgroud)

我的Master VB背后的Asp.Net代码

<WebMethod> _
Public Shared Function GetDate() As String
    Return DateTime.Now.ToString()
End Function
Run Code Online (Sandbox Code Playgroud)

目前,除非我将Web方法移动到Default.aspxVB页面,否则这不起作用

有没有办法可以改变这一部分

url: "Default.aspx/GetDate",
Run Code Online (Sandbox Code Playgroud)

要使用母版页功能?

我试着改成它

url: "template.master/GetDate",
Run Code Online (Sandbox Code Playgroud)

但这只是给我一个404错误

有任何想法吗?

提前致谢

Sha*_*ake 9

您的webmethod代码不能驻留在母版页的代码隐藏中.

我发现在我的项目中包含一个实际的Web服务或WCF服务更容易,我需要从多个页面调用它们.

编辑:

要向项目添加WCF服务:

  1. 右键单击该项目
  2. 选择[WCF服务]并为其命名(即Agent.svc)
  3. 设置服务(参见http://www.codeproject.com/KB/aspnet/jQuery_To_WCF.aspx)

Stackoverflow上有一些例子......

希望有所帮助.