ASP.NET WebService返回List<>使用jQuery

时间:2014-04-02 12:45:30

标签: c# jquery asp.net ajax web-services

这是我的WebService方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

public string getlastimages()
{
    DBservices DBS = new DBservices();
    List<string> ImageUrls = new List<string>();
    try
    {
       DBS.getLastImages();
       ImageUrls = DBS.ImgUrlList;
    }
    catch(Exception ex)
    {
        throw ex;
    }

    JavaScriptSerializer js = new JavaScriptSerializer();
    string jsonImage = js.Serialize(ImageUrls);
    return jsonImage;
}

这是我在运行此方法后收到的数据:

<string xmlns="http://tempuri.org/">
["~\\images\\benny\\1149468-18.jpg","~\\images\\lior\\photo4.jpg","~\\images\\oren\\photo3.jpg","~\\images\\oren\\photo2.jpg","~\\images\\oren\\photo1.jpg"]
</string>

我是$ .ajax方法的新手,我需要帮助编写$ .ajax方法从该列表中检索此数据。 任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

您无需将List<string>转换为json格式的字符串。它将使用JavaScriptSerializer在内部处理,因为您已使用[ScriptMethod(ResponseFormat = ResponseFormat.Json)]进行了修饰。 Check MSDN

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script
[ScriptService]
public class Service: System.Web.Services.WebService 
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public List<string> getlastimages()
    {
      DBservices DBS = new DBservices();
      List<string> ImageUrls = new List<string>();
      try
      {
       DBS.getLastImages();
       ImageUrls = DBS.ImgUrlList;
      }
      catch(Exception ex)
      {
        throw ex;
      }
      return ImageUrls;
    }
}

的jQuery

$.ajax({

url:"service.asmx/getlastimages",
type:"POST",
dataType:'json',
contentType: "application/json; charset=utf-8",
success:function(data){
   var result;
   if (data.hasOwnProperty('d')) {
    result=data.d;// ASP.Net framework will add d
   }
   else
   {
    result=data;
   }
}
});