Can't set up server side processing in ASP.NET/C#

Can't set up server side processing in ASP.NET/C#

zavsezavse Posts: 1Questions: 0Answers: 0
edited April 2014 in DataTables
Hello,

I'm rather new to DataTables and have enormous problems setting up server side processing for DataTables on my .aspx page (I'm trying to get data from an .asmx webservice). I've read all the examples I found for server side processing, but still can't get it to work.

If anyone is kind enough to post a simple example (maybe something like this http://datatables.net/release-datatables/examples/server_side/server_side.html) using asp.net/C# possibly with data provided from .asmx webservice, I would much appreciate it.

Thank you very much in advanced,
Danijel

Replies

  • RobertJuradoRobertJurado Posts: 9Questions: 1Answers: 0
    edited May 2014

    I am looking for good examples too, but no luck. Most the samples are in PHP and not much in Asp.NET webforms. I am having a problem setting up a simple example with a WebService returning the data. I already checked the string (JSON Formatted) from the WebMethod and it is a valid format.

    I hope someone can help, otherwise, I will have to give up :(

    here is my Default.aspx

            <table id="tblData" class="display">
                <thead>
                    <tr>
                        <th>SystemUserID</th>
                        <th>FullName</th>
                        <th>Email</th>
                        <th>Active</th>
                    </tr>
                </thead>
            </table>
    
            <script type="text/javascript">
                    $(document).ready(function() {
                        $('#tblData').dataTable({
                            "processing": true,
                            "serverSide": true,
                            "ajax": "WebService1.asmx/GetAllUsers"
                        });
                    } );
            </script>
    

    In WebService, I have the following Method:

        [WebMethod]
        public string GetAllUsers()
        {
            string sResult = "";
    
            try
            {
    
                int nDraw = Convert.ToInt32(HttpContext.Current.Request.Params["draw"]);
                List<SystemUser> lst = Conn.GetAllUsers();
    
                ReturnData oResult = new ReturnData();
                oResult.draw = nDraw;
                oResult.recordsTotal = lst.Count;
                oResult.recordsFiltered = lst.Count;
    
                foreach (SystemUser o in lst)
                    oResult.data.Add(o.ToString());
    
                sResult = oResult.ToString();
    
            }
            catch (Exception err)
            {
                string sMsg = err.Message;
                sResult = "";
            }
    
            return sResult;
        }
    

    This is my class for the return data, I populate the _data field with individual SystemUser which the method ToString() does the array item inside of square brackets.

    public class ReturnData
    {
        private int _draw;
        private int _recordsTotal;
        private int _recordsFiltered;
        private List<String> _data = new List<string>();
    
        #region " ... Properties ... "
        <<< there are the public properties >>>
        #endregion
    
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
    
            foreach (string s in _data)
                sb.Append(s + ",");
    
            string sData = sb.ToString();
            sData = sData.Remove(sData.Count()-1, 1);       //remove last comma
    
            string sData2 = "{ \"draw\": " + this._draw.ToString() + ", \"recordsTotal\": " + 
                            this._recordsTotal.ToString() + ", \"recordsFiltered\": " + 
                            this._recordsFiltered.ToString()  + ", \"data\": [ " + 
                            sData + " ] }";
    
            // testing purposes...
            File.WriteAllText("c:\\temp\\SampleSystemUsers.txt", sData2);
    
            return sData2;
        }
    
    }
    

    The value of sData2 (right above) is like this:

    {
        "draw": 1,
        "recordsTotal": 238,
        "recordsFiltered": 238,
        "data": [
            [
                "0",
                "",
                "Test@test.com",
                "True"
            ],
            [
                "1",
                "Var Fox",
                "Test@test.com",
                "True"
            ],
    
        Skip most of items 
    
            [
                "269",
                "Adrienne Sidley",
                "Test@test.com",
                "True"
            ],
            [
                "270",
                "Gregory Lindstrom",
                "Test@test.com",
                "True"
            ]
        ]
    }
    

    I checked the string value of sData2 in a JSON validator JSONLint and it says that it is okay, however, I keep getting the popup error saying that the

    DataTables warning: tableid=tblData - Invalid JSON response

    Any ideas... I have a feeling that i am not setting up the JavaScript correctly.

    Thanks in advance.

    Robert J.

  • RobertJuradoRobertJurado Posts: 9Questions: 1Answers: 0

    Sorry for the format... it was nice when I wrote it but the Markdown is just weird.

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    If you are getting an error saying "Invalid JSON" then - that's the problem :-). This tech note (1) provides guidance on how to see exactly what the server is returning.

    Allan

  • RobertJuradoRobertJurado Posts: 9Questions: 1Answers: 0

    Hi Allan,
    Strangely, when I intercept the JSON string inside the WebMethod and I save it in a text file and then I modified my page like this:

         <script type="text/javascript">
            $(document).ready(function () {
                $('#tblData').dataTable({
                    processing : true,
                    //serverSide : true,
                    //ajax: "WebService1.asmx/GetAll",
                    ajax : "data/data2.txt",
                    columns : [
                        { "data" : "OrderID" },
                        { "data" : "Status" },
                        { "data" : "Email" },
                        { "data" : "Phone" }
                    ]
                });
            });
        </script>
    

    It works!! Do I have somehow modify my result? LIke I said, I get the result, use a JSON validator and it says that is is fine.

    Any ideas? Thanks in advance.

    Robert Jurado.

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    My guess is that you are returning a string that contains valid JSON, rather than just a plain JSON object. However I would need a test case or a debug trace to be able to confirm that.

    Allan

  • RobertJuradoRobertJurado Posts: 9Questions: 1Answers: 0

    Hi Allan,
    Thank you, I am hoping that will be helpful. I got the code "ofenah" from the debug trace.

    Thank you

    Robert J.

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    edited May 2014

    That is very certainly not valid JSON that is being returned:

    System.InvalidOperationException: There was an error generating the XML document.-- > System.InvalidOperationException: The type DataTablesNETSample.Entities.Order was not expected.Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
    at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_ReturnData(String n, String ns, ReturnData o, Boolean isNullable, Boolean needType)
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write3_ReturnData(Object o)
    at Microsoft.Xml.Serialization.GeneratedAssembly.ReturnDataSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
    at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)---End of inner exception stack trace---at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
    at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
    at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
    at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
    at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
    at System.Web.Services.Protocols.WebServiceHandler.Invoke()
    

    Think you might need to debug your server-side script...

    Allan

  • RobertJuradoRobertJurado Posts: 9Questions: 1Answers: 0

    Hi Allan,
    Thanks for this information, it might help me to figure out this problem

    Robert J.

  • RobertJuradoRobertJurado Posts: 9Questions: 1Answers: 0

    Hi Allan,
    I just realized that the previous result was on my many different attempts to make this work. This one "eqixax" is how I get a Status code 200. and a "good" result.

    Thank you

    Robert Jurado

  • danijelvalenticdanijelvalentic Posts: 1Questions: 0Answers: 0

    Hi Robert,

    Can you please post a simple example (client side and server side code that worked for you) for the rest of us that simply can't get it right? Can you maybe also tell us what was the fix that made it work for you?

    Thank you in advanced,
    Danijel

  • srainsrain Posts: 11Questions: 4Answers: 0

    Anyone got this right?

This discussion has been closed.