2

I am trying to use Datatables within my webforms application. unfortunatly I get the whole html page instead of json data :'( this is my code.

<script type="text/javascript">
    $(document).ready(function () {
        $('#grid').dataTable({
            "dataType": 'JSON',
            "bServerSide": true,
            "sAjaxSource": 'GategoriesManagement.aspx/GetPersonList',
            "bProcessing": true,
            "aoColumns": [

                            { "sName": "d.name" },
            ]

        });
    });

</script>

my webmethod

  [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string GetPersonList()
    {
        List<personne> personeList = new List<personne>();

        personne person = new personne();
        person.name = "test1";
        personeList.Add(person);

        person = new personne();
        person.name = "test2";

        person = new personne();
        person.name = "test3";

        personeList.Add(person);
        FormatedList list = new FormatedList();

        list.iTotalDisplayRecords = 10;
        list.iTotalRecords = 200;
        list.aaData = personeList;

        var javaScriptSerializer = new JavaScriptSerializer();
        string jsonString = javaScriptSerializer.Serialize(list);
        return jsonString;
    }

and this is the alert that I get in the browser

 DataTables warning: table id={id} - Ajax error 

it appear that my webmethod is not accessible what should I do ???

4
  • Hi, can you move the webmethod to a separate WebService, e.g. GategoriesManagement.asmx/GetPersonList? And is 'Gategories' a typo, should it read 'Categories' or 'GetCategories'? Commented May 11, 2015 at 13:55
  • I need to use it as it's aspx. when I use it in a simple ajax call it work fine and I get my Json data so I need to know if there is some thing that was modified in .net 4.5 Commented May 11, 2015 at 14:00
  • And is your json data matching the required format (datatables.net/manual/server-side#Returned-data), i.e. does it look like this (datatables.net/manual/server-side#Example-data)? Commented May 11, 2015 at 14:06
  • when I call my method from PageMethods it return exactly this format but when I call it throw datatables it return a full html page.I add [ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet = true)] tag to the web method but in vain . Commented May 11, 2015 at 14:11

2 Answers 2

1

The magic piece of code which makes this work as of 1.10.12 is the ajax parameter. ASP.NET wraps JSON results in the .d property, so you need to execute the callback on that object.

    $('#tableId').dataTable(
    {
        "processing": true,
        "serverSide": true,
        "stateSave": false,
        "lengthMenu": [[10, 30, 100, -1], [10, 30, 100, "All"]],  // 1st = page length values, 2nd = displayed options
        ajax: function (data, callback, settings) {
            $.ajax({
                url: "/UserService.asmx/GetUsers",
                type: 'POST',
                contentType: 'application/json',
                dataType: "json",
                data: JSON.stringify(data),
                success: function (data) {
                    $spinner.hide();
                    callback(data.d); // execute the callback function on the wrapped data
                }
            });
        },
Sign up to request clarification or add additional context in comments.

Comments

0

I really liked @Echilon answer, but I'd like to add that it's possible to send the Ajax request as GET too.

Having said that, and although OP's example didn't include a parameter in the GetPersonList() method, I'd like to show how parameters would need to be sent on an Ajax request depending if it's a GET or POST** request:

POST request

It doesn't matter if the value is of type int, string, boolean or an object, the way to send data is the same that @Echilon showed. Although here's a little variation:

data: function (data) {

    data.parameterName = value;
    return JSON.stringify(data);
}

And here's a brief example. Let's suppose that this is your original method:

[WebMethod]
//The parameter could be a int, string or bool
public static string GetPersonList(int|string|bool value)
{
    //do something here...
}

And in your Ajax call:

$('#tableId').dataTable(
{
    //your DataTable options here
    $.ajax({
        url: "/UserService.asmx/GetUsers",
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        //dataType: "json", only include this if you're expecting the result in json format
        data: function (data) {

            data.value = 10|"Test"|false; //Send the appropriate data according to the parameter type in your method
            return JSON.stringify(data);
        },
        dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
    },
    // your columns settings here
});

In case you need to send an object here's a brief example. Let's suppose that this is your original method:

class Person
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

[WebMethod]
public static string GetPersonList(Person person)
{
    //do something here...
}

Then in your Ajax call:

var $person = {};
$person.Id = 9;
$person.UserName = "jsmith";

$('#tableId').dataTable(
{
    //your DataTable options here
    $.ajax({
        url: "/UserService.asmx/GetUsers",
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        //dataType: "json", only include this if you're expecting the result in json format
        data: function (data) {

            data.person = $person;
            return JSON.stringify(data);
        },
        dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
    },
    // your columns settings here
});

GET request

If you prefer to use a GET request, then the way to send the data varies a little. If the value is of type int or boolean, you can send it like this:

data: function (data) {

    data.parameterName = value;
    return data;
}

But if you want to send a string or an object, then you can send it like this:

data: function (data) {

    data.parameterName = JSON.stringify(value);
    return data;
}

Let's see a brief example. Let's suppose that this is your original method:

[WebMethod]
[ScriptMethod(UseHttpGet = true)] // I didn't include the ResponseFormat parameter because its default value is json
//The parameter could be a int or bool
public static string GetPersonList(int|bool value)
{
    //do something here...
}

And in your Ajax call:

$('#tableId').dataTable(
{
    //your DataTable options here
    $.ajax({
        url: "/UserService.asmx/GetUsers",
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        //dataType: "json", only include this if you're expecting the result in json format
        data: function (data) {

            data.value = 10|false; //Send the appropriate data according to the parameter type in your method
            return data;
    },
        dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
    },
    // your columns settings here
});

In case you need to send a string or an object here's a brief example. Let's suppose that this is your original method:

class Person
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

[WebMethod]
[ScriptMethod(UseHttpGet = true)] // I didn't include the ResponseFormat parameter because its default value is json
//The parameter could be an object or a string
public static string GetPersonList(Person person) // or (string value)
{
    //do something here...
}

Then in your Ajax call:

var $person = {};
$person.Id = 9;
$person.UserName = "jsmith";

$('#tableId').dataTable(
{
    //your DataTable options here
    $.ajax({
        url: "/UserService.asmx/GetUsers",
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        //dataType: "json", only include this if you're expecting the result in json format
        data: function (data) {

            data.person = JSON.stringify($country);
            //data.value = JSON.stringify("Test"); Or this one, depending the parameter of your method
            return data;
    },
        dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
    },
    // your columns settings here
});

Comments

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.