add a row to a jquery datatable. for editing

I have a datatable that is loaded on my page....and I just need to insert a row so my user can input data and save. I cannot  seem to make this happen....

Here is the jquery table referenced in the view:  I would think I could reference that table since its already loaded on page but having no luck.  Please help.

The columns that are rendered with existing data are Entity, Role, Designate, Allocation

within the jquery grid I am dynamically pulling the data ...Entity would be autopopulated, Role would load a dropdown, designate would load a drop down, and allocation would be a input for decimal values.  Then there would be an save and cancel button

<div class="col-xs-12">
        <div class="row" style="margin-bottom:4px;">

            @BootstrapHelper.Panel("GenericGrid-panel", BootstrapPanelCssClass.Primary, @Model.HeaderTextLeft, "",
                        false, @Model.Icon, "GenericGrid-panel-body", "",

                            <div id="contactEntity-crud-div" class="col-xs-12" style="float:left;display:block">
                                <div id="main-container-contactEntity" class="container-fluid">

                                    <table id='contactEntity-crud' class="display" style="width:100%;"><tbody></tbody></table>
                        </text>, "", "",@<text>  </text>)


Open in new window

LVL 11
Robb HillSenior .Net DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Leonidas DosasCommented:
Do you use  the jquery datatables plugin?
Robb HillSenior .Net DeveloperAuthor Commented:
im using the jquery library for datatables.

This table is loaded on the page by an external js handles way more than this table....

My table loads on page fine.....its just I cannot add a row.

Do I need to recall the data just to let user add a row at the top or bottom of the table..preferablly the top
Robb HillSenior .Net DeveloperAuthor Commented:
this is alot of overkill..but maybe it can help you understand how this is guessing I need to build an insertrow method in this js file.

var Page = {};
function loadGridAsync(grids, siteCode, dataWhereClause, searchFor, sortBy, childRowUrl) {

    setTimeout(function () {
        loadGrid(grids, siteCode, dataWhereClause, searchFor, sortBy, childRowUrl);
    }, 0);


function loadGrid(grids, siteCode, dataWhereClause, searchFor, sortBy, childRowUrl) {

    var schemaResults;
    var columns;
    var columnDefs;
    var errorMessage;

    if (siteCode == null ||  siteCode == "") {
        siteCode = "";
    else {
        siteCode = "," + siteCode + ","; // to provide delimiters on both sides;

    var gridNameArr = grids.replace(' ','').split(',');

    for (var g in gridNameArr) {

        var gArr = gridNameArr[g].split('^');
        var gridName = gArr[0];
        var afterRenderCallBack = gArr[1];
        var $this = UI.Html;
        var $cUtil = Utilities;
        var $cMesg = UI.Messenging;
        var schemaApi = "/GenericGrid.mvc/GenericGridDataTable?gridName=" + gridName + "&sitecode=" + siteCode + "&searchFor=" + searchFor + "&mode=schema&SessionID=" + Conarc.Utilities.Http.getSessionId();
        var dataApi = "/GenericGrid.mvc/GenericGridDataTable?gridName=" + gridName + "&sitecode=" + siteCode + "&searchFor=" + searchFor + "&mode=data&SessionID=" + Conarc.Utilities.Http.getSessionId() + "&whereClause=" + encodeURIComponent(dataWhereClause);
        var propertiesApi = "/GenericGrid.mvc/GenericGridDataTable?gridName=" + gridName + "&sitecode=" + siteCode + "&searchFor=" + searchFor + "&mode=props&SessionID=" + Utilities.Http.getSessionId();

            async: false

        var schemaPromise = [$.getJSON(schemaApi)];
        $.when.apply($, schemaPromise).done(function (schemaData) {

            //check if data came from WebAPI or MVC controller (string vs object)

            if (!$cUtil.String.isNullOrEmpty(schemaData)) {
                schemaResults = JSON.parse(schemaData);
            } else {
                schemaResults = schemaData;
            if (!$cUtil.Object.isNullOrNotObject(schemaResults)) {

                var tableElementId = gridName;
                var tableHtml = $this.getHtmlTableByColumns(schemaResults, tableElementId, '');
                var containerIdSelector = "#" + tableElementId;

                if ($(containerIdSelector).length > 0) { 
                    $(containerIdSelector + "-div").empty().append(tableHtml);

                $(containerIdSelector + "-div").show();

                //get column arrays
                columns = $this.getDataTableColumns(schemaResults);
                columnDefs = $this.getDataTableColumnDefs(schemaResults);

                var sortIndex = 0;
                var sortDirection = "asc";
                var sColumns = "";

                    async: false

                //get datatable properties
                    type: "GET",
                    url: propertiesApi,
                    cache: false,
                    dataType: "html",
                    success: function (data) {

                        var a = jQuery.parseJSON(data)[0];
                        if (a === undefined) {


                        // find a[0].defaultSortColumn in sColumns to set order #
                        var c = 0;
                        columns.forEach(function (e) {
                            sColumns += + ",";
                            if ( == a.defaultSortColumn.toLowerCase()) {
                                sortIndex = c;

                        if (a.sortDescending) {
                            sortDirection = "desc";

                        $.fn.dataTable.ext.errMode = function (settings, helpPage, message) {

                            async: false

                            dom: '<"top"f>rtip',
                            ajax: dataApi + "&sSortColumn=" + a.defaultSortColumn + "&sSortDir=" + sortDirection,
                            deferRender: true,
                            scrollY: a.height,
                            scrollCollapse: a.collapse,
                            scrollX: true,
                            responsive: false,
                            scrollcollapse: true,
                            scroller: true,
                            columns: columns,
                            columnDefs: columnDefs,
                            autoWidth: true,
                            fixedColumns: {
                                heightMatch: 'auto'
                            destroy: true,
                            bFilter: a.showSearchBox,
                            sColumns: sColumns,
                            order: [[sortIndex, sortDirection]],
                            info: a.collapse,  // hide "Showing x of y" RSS TODO NEED Separate option for grids

                            "createdRow": function (row, data, index) {
                                if (data.dueDateLate) {
                                    $('td', row).eq(4).addClass('dueDateLate')

                        })).success(function (data) {

                            var table = $(containerIdSelector).DataTable();


                            var fn = window[afterRenderCallBack];
                            if (typeof fn === "function") {


                            // set up event to display child rows
                            if (childRowUrl != '') {

                                $('#' + gridName + ' tbody').on('click', 'td.expand', function (e) {
                                    getChildRows(e, gridName, childRowUrl);
                        }).fail(function (error) {


                        $(containerIdSelector + "-div").show();
                    error: function (data) {

            } //end of if schemaResults object check
            else {
                errorMessage = "Error: couldn't convert schema information from API to object.  Please contact support.";
                $cMesg.getErrorPopup(errorMessage, "Error: Schema Loading", 9000);

            } //end of else schemaResults not object

            var table = $(containerIdSelector).DataTable();


function StreamFile(title, documentCode) {
    UI.Messenging.getInfoPopup(title, "Getting ...");"/wc.dll?CADOC~CADOCMANAGE~DMDOCUMENTS~FILESNAP~" + documentCode);

//function PrintFile(title, documentCode) {
//    UI.Messenging.getInfoPopup(title, "Getting ...");
//   // window.print("/wc.dll?CADOC~CADOCMANAGE~DMDOCUMENTS~FILESNAP~" + documentCode);

function CollapseGrid(gridBodyId, gridId) {
    $('#' + gridBodyId).hide();
    $('#collapseGridIcon-' + gridId).hide();
    $('#expandGridIcon-' + gridId).show();

function ExpandGrid(gridBodyId, gridId) {
    $('#' + gridBodyId).show();
    $('#collapseGridIcon-' + gridId).show();
    $('#expandGridIcon-' + gridId).hide();

function getQueryVariable(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(;
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

function AdjustColumns(gridName) {
    if (gridName == '') {
        gridName = $("#hGridName").val();
    var table = $("#" + gridName).DataTable();
function ReDrawTable() {

    // where we are is saved here... retrieve it
    var gridName = $("#hGridName").val()

    var siteCode = $("#hSiteCode").val();
    var dataWhereClause = $("#hWhereClause").val();
    var searchFor = $("#searchBox").val();
    var sortBy = $("#hSortBy").val();
    var childUrl = $("#hGetChildUrl").val();
    loadGridAsync(gridName, siteCode, dataWhereClause, searchFor, sortBy, childUrl);

function expandRow(e, table, row, tr, data) {
    if (row.child.isShown()) {

    else {
        var tmpRow = table.row.add(data).draw().node();




Open in new window

Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Leonidas DosasCommented:
In general, what you can do is create a row object and then within that row object whenever you run a loop to place the prices on the corresponding children of the item .

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Robb HillSenior .Net DeveloperAuthor Commented:
I dont follow....

So for me to execute the following javascript above I call this.:  Now this is hardcoding some values..but basically it goes to my get the structure of the table....then calls the javascript above...where the loadgrid is the big call.  After this is page loads up with a grid of column headers, and data from my sql database...and some dynamic buttons.    I just want to be able to add a row a user can insert new data into this table.

    $(document).ready(function () {

     var grids = "contactEntity-crud";
     var sortBy = $("#hSortBy").val();
     loadGridAsync(grids, "", "contactId=69789", "", sortBy,"");

Open in new window

Robb HillSenior .Net DeveloperAuthor Commented:
i added this...and it appears that it adds the row...but you cannot actually see anything.....but the row count increments.....not sure what this means at this point..  I just put fake info I would really be adding controls.not data.

    function addNewRow(){
        var table = $('#contactEntity-crud').DataTable();
 table.row.add( [
            'New row',
            'Test 2',
        ] ).draw();

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.