2009-07-24 28 views
10

如何在jQuery上使用getJSON方法调用ASP.NET Web Form页面上的方法?将jQuery的getJSON方法与ASP.NET Web表单一起使用

的目标是:

  1. 一个列表项用户点击
  2. 值发送到使用JSON
  3. 填充辅助服务器
  4. 服务器用的东西相关的列表来做出响应,格式化盒子

我不想使用UpdatePanel,我使用ASP.NET MVC框架完成了数百次,但不能使用Web窗体找出它!

到目前为止,我可以做的一切,包括调用服务器,它只是不调用正确的方法。

感谢,
基隆

一些代码:

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

回答

24

这里是一个简约的例子会告诉你如何开始:

<%@ 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

我调整你的代码位。我将ClientID的服务器端输出添加到updateRegions方法以传递它。并且我更改了getJSON方法,以便使用查询字符串参数(而不是单独的数据)和回调函数传递url。

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

让我知道,如果这有效!

0

您还可以使用的getJSON,但你应该改变这种情况下的WebMethod。

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

做一个GET可能不是你想要什么:你应该和装饰它。