1

I want to display the data from database on some time interval so I used Timer control, but on every tick fire the div (chat box) minimizing, so I want to avoid this minimizing on every post back I used Jquery to webmethode concept like below.

to call C# array type webmethod.

<script type="text/javascript">
        $(document).ready(function () {           
            $("#tblCustomers tbody tr").remove();
            $.ajax({
                type: "POST",
                url: "GetDataByJquery.aspx/GetMessages",
                data: '{roomId: "' + $("[id$=lblRoomId]").html() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        var rows = "<tr>"
                    + "<td class='customertd'>" + item.Username + "</td>"
                    + "<td class='customertd'>" + item.Sex + "</td>"
                    + "<td class='customertd'>" + item.Text + "</td>"
                    + "<td class='customertd'>" + item.TimeStamp + "</td>"
                    + "<td class='customertd'>" + item.UserID + "</td>"
                    + "</tr>";
                        $('#tblCustomers tbody').append(rows);
                    }))
                },
                failure: function (response) {
                    alert(response.d);
                }
            });
        });    
    </script>

Got data from sqlserver and reterning in array.

    public static Messages[] GetMessages(string roomId)
    {
        List<Messages> messages = new List<Messages>();           
        string strConnString = ConfigurationManager.ConnectionStrings["LinqChatConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                string query = "[Get_Messages]";
                SqlCommand cmd = new SqlCommand(query);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@roomId", roomId);
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    Messages message = new Messages();
                    message.Username = reader.GetString(0);
                    message.Sex = reader.GetString(1);
                    message.Text = reader.GetString(2);
                    message.TimeStamp = reader.GetDateTime(3);
                    message.UserID = reader.GetInt32(4);
                    messages.Add(message);
                }
            }
        }
        return messages.ToArray();
    }

but I can't display the data..so how to display it?

4
  • 1
    You need to use NewtonSoft.json. There is a method to serialize an object to JSON format. Commented Aug 26, 2015 at 9:56
  • Can you give any example please on my condition?. Commented Aug 26, 2015 at 9:57
  • Watch the below answer by @Pavan, it looks exact solution to your problem. Commented Aug 26, 2015 at 10:10
  • throwing an compile time error : Cannot implicitly convert type 'string' to 'ChatApp.Messages[]' .. at 'return result'. Commented Aug 26, 2015 at 10:43

3 Answers 3

2

Use Newtonsoft.Json to serialize an Object to JSON.

Set the response content-type to application/json and serialize the result object and return it.

    HttpContext.Current.Response.ContentType = "application/json";
    var result= JsonConvert.SerializeObject(messages);
    return result;

To install Newtonsoft.Json

Right click on your references folder in your solution explorer and select "Manage Nuget Packages", a wizard will be there.

Write Newtonsoft in search box, it will show Json.Net on top.

Click Install, it will take a few seconds to install.

Sign up to request clarification or add additional context in comments.

10 Comments

is the 'Newtonsoft.Json' library file?
I added 'Newtonsoft.Json' dll in reference so which namespace I have to use ?
using Newtonsoft.Json;
throwing an compile time error : Cannot implicitly convert type 'string' to 'ChatApp.Messages[]' .. at 'return result'.
change the return type of your function :)
|
0

Issue is not about WebMethod, it is when data returns to client i.e. in $.ajax, success callback, you are not correctly using $.map function and you are also using undefined method response (this method is not exist in your code), which leads to JS error and data is not displayed.

So change the code

success: function (data) {
   response($.map(data.d, function (item) {
      var rows = "<tr>"
      + "<td class='customertd'>" + item.Username + "</td>"
      + "<td class='customertd'>" + item.Sex + "</td>"
      + "<td class='customertd'>" + item.Text + "</td>"
      + "<td class='customertd'>" + item.TimeStamp + "</td>"
      + "<td class='customertd'>" + item.UserID + "</td>"
      + "</tr>";
      $('#tblCustomers tbody').append(rows);
     }))
  }

To

success: function (data) {
   var rows = $.map(data.d, function (item) {
      return "<tr>"
      + "<td class='customertd'>" + item.Username + "</td>"
      + "<td class='customertd'>" + item.Sex + "</td>"
      + "<td class='customertd'>" + item.Text + "</td>"
      + "<td class='customertd'>" + item.TimeStamp + "</td>"
      + "<td class='customertd'>" + item.UserID + "</td>"
      + "</tr>";
    });
    $('#tblCustomers tbody').append(rows);
 }

Explanation of this code:

$.map function is used to transform collection into another collection. So we are working on data.d and for every iteration, we transform object to html which contains a row and return that html tr row in $.map function body,and we are storing this all returned tr html in a local variable “var rows=…”.

So when $.map will exit, we will have all transformed tr html in variable rows, and we can append it in the table’s tbody, which results in data displayed in table format.

2 Comments

This code also not displaying any row/column in a table.
@ArmaanAhmed, Are you able to get data on your success callback handler or not? try to log it on console, like console.log(data.d) on chrome. If you are getting that, its mean WebMethod is working fine, if not getting that then something wrong with WebMethod.
0

You can also use the JsonResult as below code in order to return serialize object.

    [WebMethod]
    public JsonResult testmethod()
    {
        List<YourObject> objectlist = new List<YourObject>();
        JsonResult result = new JsonResult();
        result.Data = objectlist;
        return result;
    }

1 Comment

I cant Use 'JsonResult', where it is?

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.