4

Am trying JQUERY DataTable with MVC. First thing am trying to do is trying to set up the base.

Am trying to get the column and Datavalues Dynamically. am using fnServerData with sAjaxSource.

Am having a breakpoint in my controller file to see if the it is getting called to make sue i have set it up correctly before proceeding.

When i run this code. Am getting "TypeError: k is undefined" so controller is not getting called

When is searched for this issue closer i came is jQuery datatables issue which states

In order for DataTables to be able to function correctly, the HTML for the target table must be laid out in a well formed manner with the 'thead' and 'tbody' sections declared.

But am forming everyting dynamically so am not sure what am doing wrong. My sample code below.

Any suggestions on doing it the right way would help !

CSHMTL file

<table id="TestDatatable">

</table>

DataTable script file

$('#TestDatatable').dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "Search/Testcall",
        "fnServerData": function (sSource, aoData, fnCallback, oSettings) {
            aoData.push({ "name": "more_data", "value": "my_value" });
            oSettings.jqXHR = $.ajax({
                "dataType": 'json',
                "type": "POST",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            });
        }
    });

Sample Model

public class DataTableParam
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho { get; set; }

        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch { get; set; }

        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength { get; set; }

        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart { get; set; }
}

Controller

public JsonResult Testcall(DataTableParam searchData)
        {
         return Json("", JsonRequestBehavior.AllowGet); 
        }

Update

Another update which i got while going through the issue is we need to set the Columns first before we assign data to DataTable. But in my scenario am trying to hit controller in an ajax call but even before that am getting the above Error.

Update

Is Dynamic DataTable not possible at all ? I ll know the Columns as well as Data only at runtime?

Thanks

4
  • well first problem i see is yout table html is not fully formed, datatables requires full table thead tbody declaration, all with proper tr and syntax Commented May 31, 2013 at 15:14
  • Agree. How about when i form it dynamically ? and second point is my controller parameters are null when ajax call is received ! Commented Jun 3, 2013 at 4:39
  • I am going to stumble thru this with you as asp.net mvc is not my forte...i notice your controller is set to allow get, but your fnServerData ajax is submitting via post, set that to get , as for dynamically generated table structure, as long as it is prior to the DOM being loaded, should be fine, but typically i always do statc html for the table (makes things easier in long run) Commented Jun 4, 2013 at 0:38
  • Allowget is for allowing the JQOERY to have access to JSON Data. And what the purpose of static table in real time ? what if you have to show 1 lakh records from Table ? we need server side pagination and sorting else things will mess up! Commented Jun 6, 2013 at 9:04

3 Answers 3

1

EDIT#1

The reason you are getting a type error is due to the malformed table which you seemed to already know. You also mentioned the table is being created dynamically, so we are going to attempt adding the table header dynamically using server code to dynamically write the columns

sTitle will provide table headers in absentia (sClass just supplies a row class)

<script type="text/javascript>
    $('#TestDatatable').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "Search/Testcall",
            "aoColumns": [
            { "sTitle": "Engine" },
            { "sTitle": "Browser" },
            { "sTitle": "Platform" },
            { "sTitle": "Version", "sClass": "center" },
            { "sTitle": "Grade", "sClass": "center" }
        ], ...

What would have to happen is creating an initial query to run prior to the ajax query (as they are not related).

Purpose of this query is collect the table column names, it can be the same query as the original, we just need the column names (please excuse my asp.net syntax, not sure if correct but you'll get the idea)

Datatables function

<script type="text/javascript>
        $('#TestDatatable').dataTable({
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": "Search/Testcall",
                "aoColumns": [
    <% for each ColumnList as Column
        { '{ "sTitle": "'& Column &'" },' } 
    %>
                ], //aoColumns end
                "fnServerData": function (sSource, aoData, fnCallback, oSettings) {
                    aoData.push({ "name": "more_data", "value": "my_value" });
                    oSettings.jqXHR = $.ajax({
                        "dataType": 'json',
                        "type": "POST",
                        "url": sSource,
                        "data": aoData,
                        "success": fnCallback
                    });
                }
            });
</script>

the above is theoretical but should work

Original Answer The reason you are getting a type error is due to the malformed table which you seemed to already know. You also mentioned the table is being created dynamically

Best way: let datatables do the work for you

<table>
    <thead><tr><th>Group</th><th>Code</th><th>Account</th><th>Type</th></tr></thead>
<tbody></tbody>
</table>

Above is all you will need for html in your cshtml file

Now your json call needs to actually return data (baby steps)

Im not that familiar with json encoding in asp.net, i typically use ashx handlers in c# when dealing with .net, however the bottom line is the ajax url you use needs to return the following json for server side implementations, exception for dt_rowid and dtrowclass, they are just optional fields to either assign tr rows ids or classes)

{
    "sEcho": 3,
    "iTotalRecords": 57,
    "iTotalDisplayRecords": 57,
    "aaData": [
        {
            "DT_RowId": "row_7",
            "DT_RowClass": "gradeA",
            "0": "Gecko",
            "1": "Firefox 1.0",
            "2": "Win 98+ / OSX.2+",
            "3": "1.7",
            "4": "A"
        },
...

Datatables will generate the tr td html for you if you give it well-formed json

Finally, your datatables function will need bServerSide set true, and your fnRowCallback appears to be in order

Previous way i did things which did not utilize the power of datatables:

<table>
    <thead><tr><th>Group</th><th>Code</th><th>Account</th><th>Type</th></tr></thead>
<tbody>
 @foreach ( var i in dataset)
{ '<tr><td>...</td></tr>' }

</tbody>
</table>

Docs to refer to typeerror From the usage page:

In order for DataTables to be able to function correctly, the HTML for the target table must be laid out in a well formed manner with the 'thead' and 'tbody' sections declared.

In your case, the <thead> and <tbody> sections are missing...add those to fix your typeerror k being undefined

We can fix the ajax after the type error resolution, but initially, it appears your controller is set to get, while your datatables ajax is set to post, set the ajax to get and see if that resolves the issue

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

2 Comments

My question relates to forming dataTable Dynamically. I know the columns and Data only at run time? Is this feasuible in DataTable ?
@JayRizzi: i need some help, pls have a look at my question stackoverflow.com/questions/16982166/…
1

Try adding sName parameter to aoColumnDefs, following @JayRizzi initialization example:

<script type="text/javascript>
$('#TestDatatable').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "Search/Testcall",
    "aoColumns": [
    { "sTitle": "Engine", "sName": "engine" },
    { "sTitle": "Browser", "sName": "browser" },
    { "sTitle": "Platform", "sName": "platform" },
], ...

sName argument must match object attribute name in the JSON you sent from server. In your example I suppose that would by name and value. Also, if you specify sAjaxSource and the response is the JSON object you need (i.e. page.php echoes json_encode(something)), you will do just fine without invoking fnServerData.

Comments

0

Please make sure you have added the dataTable class to the table tag:

<table class="dataTable">

Enjoy!

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.