【问题标题】:ASP.NET WebService returning List<> using jQueryASP.NET WebService 使用 jQuery 返回 List<>
【发布时间】:2014-04-02 12:45:29
【问题描述】:

这是我的 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 方法以从该列表中检索此数据。 任何帮助都会很棒。

【问题讨论】:

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


    【解决方案1】:

    您无需将List&lt;string&gt; 转换为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;
       }
    }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 2017-11-01
      • 2014-04-01
      • 1970-01-01
      相关资源
      最近更新 更多