Search code examples
asp.netajaxwebformsresponsewebmethod

Returning json objects from a WebSerice in an Ajax Response


I'm trying to return json objects from a Webservice (ASP.NET WebForms application) into an Ajax success response. Although data is being returned in the Webservice, no data is making it to the Ajax response.

Here's the WebService:

[WebMethod]
public List<Images> GetImageObj()
{
    List<Images> all = new List<Images>();
    Images infoObjs = new Images();
    ImageLoading iload = new ImageLoading();
    DataTable dtImages = iload.GetData();
    foreach (DataRow row in dtImages.Rows)
    {
        infoObjs.ID = Convert.ToInt32(row["FILE_ID"].ToString());
        Byte[] bytes = ((Byte[])row["THUMBNAIL_CONTENT"]);
        infoObjs.ImageURI = iload.GetImage(bytes);
        all.Add(infoObjs);
    }            
    return all;
}

public class Images
{
    public List<Images> imgObjs;
    public string ImageURI;
    public int ID;
}
    

Here's the Ajax Callback function:

function AjaxCall() {
    $(document).ready(function () {
        var dataArr = [];
        $.ajax({
            url: '../WebService1.asmx/GetImageObj',
            method: 'post',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: "{'aray':" + JSON.stringify(dataArr) + "}",  
            success: function (response) {   
            //No data is making it here:
                var getData = JSON.parse(response.d); 
                alert(getData);
            },
            error: function (err) {
                alert(err);
            }
        });
    });
}

UPDATE: @Julian's answer fixed my issue. However, I had to add the following to my webconfig to accommodate the large data from the encoded image URI:

 <system.web.extensions>
    <scripting>
      <webServices>
        <!-- Update this value to change the value to a larger value that can accommodate your JSON Strings -->
        <jsonSerialization maxJsonLength="86753090" />
      </webServices>
    </scripting>
  </system.web.extensions>

Solution

  • Try to return a string, but serialize the object in JSON using the Json.NewtonSoft library.

    Also add the [ScriptService] tag on the service to be consumed from Ajax:

    C# Code:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {
    
        [WebMethod]
        public string GetImageObj()
        {
            List<Images> all = new List<Images>();
    
            Images infoObjs = new Images();
            ImageLoading iload = new ImageLoading();
            DataTable dtImages = iload.GetData();
            foreach (DataRow row in dtImages.Rows)
            {
                infoObjs.ID = Convert.ToInt32(row["FILE_ID"].ToString());
                Byte[] bytes = ((Byte[])row["THUMBNAIL_CONTENT"]);
                infoObjs.ImageURI = iload.GetImage(bytes);
                all.Add(infoObjs);
            }
    
            return JsonConvert.SerializeObject(all, Formatting.Indented);
        }
    }
    

    AJAX Code:

    <script type="text/javascript">
    
        $(document).ready(function () {
    
            var dataArr = [];
            $.ajax({
                url: '../WebService.asmx/GetImageObj',
                method: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: "{}",  
                success: function (response) {   
                    //No data is making it here:
                    var getData = JSON.parse(response.d); 
                    console.log(getData);
                },
                error: function (err) {
                    console.log(err);
                }
            });
    
        });
    
    </script>