2009-07-24 66 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可能不是你想要什麼:你應該和裝飾它。