2

I made this web service that returns a datatable from sql server db. Can someone help me with the jquery to display it?

web service

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]
public class WebService : System.Web.Services.WebService
{
  DataTable dt = new DataTable();

  [WebMethod]
  public DataTable dbAccess()
  {
    using (SqlConnection conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["localConnectionString"]
           .ConnectionString))
    {
      using (SqlDataAdapter da = new SqlDataAdapter())
      {
        conn.Open();
        da.SelectCommand = 
             new SqlCommand("SELECT VehicleMake FROM VehicleMakes", conn);
        da.Fill(dt);  
      }
      conn.Close();
    }
    return dt;   
  }   
}

and this is as far as I got with the jquery

<script type="text/javascript">

    $(function () {
        $('#Button1').click(getData);
    });

    function getData() {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/dbAccess",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                // What goes here?
            },
            failure: function (msg) {
                //error message
            }
        });
    }
</script>
3
  • I thought you needed WCF to provide Json data, like this: west-wind.com/weblog/posts/164419.aspx Commented Nov 14, 2010 at 20:53
  • 1
    @Albin, with the [ScriptService] attribute, a web service will return JSON, no WCF required. Commented Nov 14, 2010 at 22:50
  • But, how to get the DataTable using JSON and get each row of DataTable using JSON? Commented Dec 2, 2013 at 9:46

4 Answers 4

3

In the past, when using asmx services with jQuery, I used something like the following for post/json:

Assuming that I had a response class like this:

    public ResponseClass
    {
        public string Message { get; set; }
    }

And a webservice with a method like this:

    [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public ResponseClass PostResponse()
    {
        var response = new ResponseClass() {Message = "Hello World"};
        return response;
    }

Some html like this:

<div id="response">
</div>

The javascript:

$.ajax({
    url: '/MyService.asmx/PostResponse',
    data: "{}",
    type: "POST",
    cache: false,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        var response = msg.d; //your response object
        $('#response').html(response.Message); //set the response div contents to the Message 
    },
    error: function(xhr, status, error) {
        alert(error); //do something if there is an error
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

@nick: this is the way I have always done it, too. A tip: if you are using Firefox with Firebug, the Net pane will show the ajax request, including giving a JSON view of the response. Can be helpful when seeing how exactly complex types are being returned as JSON.
1

Just in case anyone comes by this post looking for the same answer I have provided what I came up with.

My web service communicates with a database, reads a table with a SqlDataReader and loads that data into a datatable. Each row is then stored in an ArrayList.

   [WebService(Namespace = "http://babyUnicorns.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public object dbAccess()
    {

        DataTable table = new DataTable("myTable");
        ArrayList arl = new ArrayList();
        using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString))
        { 
            using(SqlCommand comm = new SqlCommand("SELECT * FROM VehicleMakes",conn))
            {
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();
                table.Load(reader);
                reader.Close();
                conn.Close();    
            }            
        }
        foreach(DataRow dRow in table.Rows)
                {
                    arl.Add(dRow["VehicleMake"]+"  "+dRow["VehicleMakeId"]);    
                }
        return arl.ToArray();       
    }  
}

Using jQuery ajax command I take the returned arrayList and foreach item in the array I append to my div named "output". The jQuery $.each command is used to pick apart an array. I figured out how to use it by reading the API.

    function getData() {
            $.ajax({
                type: "POST",
                url: "WebService.asmx/dbAccess",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var response = msg.d;
                    $.each(response, function(index, value) {
                        $('#output').append(value+'<br />'); 
                        });              
                },
                failure: function (msg) {
                    alert('failure');
                }
            });
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" id="Button1" value="Get Cars" /><input type="button" id="buttonClear" value="Clear" />
<div id="output">

</div>
    </div>
    </form>
</body>
</html>

This returns a list of cars pulled from the database.

Comments

1
<input id="Button2" type="button" value="button" onclick="Find()" /><br /> // call the javascript function Find()

//Javascript function Find()
function Find() {
        $(document).ready(function () {
            $.ajax(
            {
                type: "POST",
                url: "Model/CustomerDTO.asmx/GetDetail",
                data: "{'nm':'" + $('#Text1').val() + "'}", // passing a parameter to retrive detail.
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                                     var obj = jQuery.parseJSON(msg.d); // parsing of Json string to Javascript object.
                    alert(obj.COMPANYADDRESS); //. anything(depends upon your Fieldname
                    $('#RSSContent').html(obj.COMPANYADDRESS); // bind data to a div

                },
                error: function () {
                    alert('data could not be be found');
                }
            });
        });

    }

Comments

0

You have multiple options

1) You can either return pure html from the back end and do .html on the div tag

2) Construct a jsonp object using stringbuild and return to the UI. In the UI you can use eval(response) and parse the object.

Let me know if you need any furthur info on this.

I have done both the approaches.

this is form my code , and you can do as below

var jsonobj = eval('(' + tempstr + ')');

            for (var i = 0; i < jsonobj.searchsuggest.items.item.length; i++) { }

2 Comments

He already has his ScriptService returning the results as JSON, he does not need to construct the JSON string himself.
sorry , i thought he is not exposing methods results as jsonp objects now, yes right recently i did the same with WCF exposing the ressponse as ajax/jsonp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.