Consuming a .NET JSON web service

5 posts, 1 answers
  1. David
    David avatar
    32 posts
    Member since:
    May 2012

    Posted 08 Jun 2012 Link to this post

    Hi;

    I'm building a .NET web service that my application will consume. I've built the service to deliver JSON data. Using the .NET serializer the data looks like this:

    [{"title":"Stuff","value":"Here's some stuff"}]
    </string>

    Here's the web service:

    [WebService(Namespace = "http://yaddayaddayadda.com/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        [ScriptService]
        public class websiteWebService : System.Web.Services.WebService
        {
            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            public string GetStuff(int stuff_id)
            {
                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["stuff"].ConnectionString);
                connection.Open();
     
                SqlCommand command = new SqlCommand("o_get_stuff", connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@stuff_id", stuff_id);
     
                SqlDataReader dr = command.ExecuteReader();
                DataTable dt = new DataTable("Stuff");
                dt.Load(dr);
                dr.Close();
                connection.Close();
     
                List<Dictionary<string, object>> rows = new
    List<Dictionary<string, object>>();
                Dictionary<string, object> row = new
    Dictionary<string, object>();
                foreach (DataRow datarow in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, datarow[col]);
                    }
                    rows.Add(row);
                }
     
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string jsonData = serializer.Serialize(rows);
                return jsonData;
            }
        }
    }


    Here is my javascript as it stands:

    <script type="text/javascript">
            $(document).ready(function () {
                $("#stuffSelector").kendoDropDownList({
                    dataTextField: "title",
                    dataValueField: "value",
                    dataSource: {
                        transport: {
                            read: {
                                contentType: "application/json",
                                type: "POST",
                                url: "http://localhost:23035/Services/websiteWebService.asmx/GetStuff",
                                data: {
                                    stuff_id: "0"
                                }
                            }
                        }
                    }
                });
            });
        </script>

    The problem I have is that the data array is wrapped in a <string>. How do I modify my datasource (or the web service) to provide just the array so that I can directly read the "title" and "value"? I'd like to drop something into the datasource schema but I don't know what will strip off the <string>.

    Thanks!
  2. Answer
    Atanas Korchev
    Admin
    Atanas Korchev avatar
    8462 posts

    Posted 11 Jun 2012 Link to this post

    Hi,

     You should not explicitly serialize your result as JSON - the web service will do this automatically for you. You can check this demo which shows how to consume an ASMX web service with Kendo. You may also find this blog post useful: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/ 


    All the best,

    Atanas Korchev
    the Telerik team
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  3. Kendo UI is VS 2017 Ready
  4. David
    David avatar
    32 posts
    Member since:
    May 2012

    Posted 11 Jun 2012 Link to this post

    Awesome advice! Thanks!

    I've got the basics of this but I'm hung up on the details. In my case I don't have a datamodel so serializing the objects can't be done exactly as in the example. My data is simple: just the datatable returned from a sql stored procedure. I've tried a bunch of means of serializing but they either fail as a circular reference or lose the field names so the js can't get at the data.

    Any advice on serializing a dataset without a datamodel?

    EDIT:

    Booyah! Here's how I managed to serialize my datatable:
    List<Template> list = new List<Template>();
    Template tmplt = new Template();
    list.Add(tmplt);
    foreach (DataRow row in dt.Rows)
    {
      tmplt.title = (string)row["title"];
      tmplt.value = (string)row["value"];
      list.Add(tmplt);
    }
     
    return list.ToList();

    Just had to add a simple class to the webservice (public class Template) and voila!
  5. Don
    Don avatar
    38 posts
    Member since:
    Oct 2006

    Posted 12 Jul 2012 Link to this post

    I am also using an .asmx web service that returns a List<SeriesData>
    (a simple class with 3 properties of type string)

    I can get this to work with $.ajax({}), but not using the kendo DataSource/transport.
    I am making a call to an external service but it has been configured to allow cross domain calls (again, works with jQuery)
    I read (alot) and found that the kendo DataSource is entirely based on $.ajax.

    so, why cant I get it to work using the transport?
    THANKS

    WORKS: 
    function loadAJAX() {                
                    jQuery.support.cors = true;
                    $.ajax({
                         type: 'POST',
                         cache: false,
                         url: remoteHost + "getCustomersFiltered_JSON",
                         contentType: 'application/json; charset=utf-8',
                         data: "{startValue: 'abc'}",
                         dataType: 'json',
                         success: onSuccess,
                         error: onError                   
                    });
                }

    DOESNT WORK:
      function createGridWithTransport()
                {
                       $("#grid").kendoGrid(
                        {
                            dataSource:  new kendo.data.DataSource(
                            {
                                transport: {
                                    read: {
                                            url:  remoteHost + "getCustomersFiltered_JSON"
                                            , data: {startValue: 'abc'}
                                            //, data: "{startValue: 'abc'}"
                                            , contentType: 'application/json; charset=utf-8'
                                            , type: 'POST'
                                            , dataType: "json"
                                          }
                                }, 
                               
                                schema: {data: "d"}
                            }),
                           
                            columns: [
                                {title: 'Name', field:'Name'},
                                {title: 'Key', field:'Key'},
                                {title: 'Value', field:'Value'}
                                ]
                            }
                    );
                   
                    alert("no JS errors");
                }
               
  6. Michael
    Michael avatar
    19 posts
    Member since:
    Oct 2011

    Posted 08 May 2013 Link to this post

    Your webservice is fundamentally flawed. You should be using standard .net objects and returning them; not serializing to JSON. See this article for a great write-up about that VERY common mistake: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

    Notice that the results will be wrapped as {d: YOUR_RESULTS} so you'll need to refer to response.d (no need to parse).
Back to Top
Kendo UI is VS 2017 Ready