从javascript调用的Web服务中检索值?

时间:2011-12-08 10:17:51

标签: c# javascript asp.net

是否可以通过从javascript调用webmethode来检索值或日期,以下是示例代码:

//This method is in a webservice.asmx file.
[WebMethod]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{

    return Cities.GetAllCitiesByCountry(CountryID: countryID);
}


<script language="javascript" type="text/javascript">

function fillCities() {
    var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>');
    var selectedIndex = dropDownList.selectedIndex;
    var value = dropDownList[selectedIndex].value;

   WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, "");

}

   function onSuccess(result){
      alert(result[0].(PropertyName));
      }

变量x没有检索任何东西,我猜它会产生错误。我试图定义一个数组,但它仍然无法正常工作。有什么想法吗?

修改

上面的代码已被更改,现在是我的问题的答案以及下面使用JQuery的答案。

3 个答案:

答案 0 :(得分:2)

在Jquery中使用Json响应,它非常酷且容易。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class CitiService : WebService
{
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<tbl_City> GetAllCitiesByCountry(int countryID)
    {
     List<tbl_City> cities = GetCities(countryID);
     JavaScriptSerializer js = new JavaScriptSerializer();
        var jsonObj = js.Serialize(cities);
        Context.Response.Clear();
        Context.Response.Write(jsonObj);
        Context.Response.End();
     }
 }

在ASp.net页面上

<script language="javascript" type="text/javascript">
 $.ajax({
        url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>',
        dataType: "json",
        data: "{countryID:'100'}",
        success: function (result) {
            alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid
        }
      });

答案 1 :(得分:1)

您可以使用JQuery和ASP.NET webmethods Encosia

轻松完成此操作

答案 2 :(得分:0)

您需要使用ScriptManager注册您的网络服务,然后从客户端进行调用。看看这个教程:

Client-Side Web Service Calls with AJAX Extensions

此外,您可以使用jQuery的Web服务,但在这种情况下,您需要切换到JSON:Calling ASMX from jQuery

相关问题