Search code examples
jqueryasp.net-mvc-3jquery-templates

JQuery template fill table problem. Need help


I have table data coming from db using $.ajax. The data is not filling right. Can someone please fix the code.

This is in javascript file

var ReloadGrid = (function(){
            $.getJSON("/HeaderMenu/GetHeaderGrid", function(data) {
                $( "#gridTemplate" ).tmpl(data).appendTo( "#mytemp" );
            });
 });

Below is in mvc3 razor page. Problem is the "mytemp" is not filling instead showing columns at the top of header returning 3 rows. num++ not working don't know where to initalize it required as counter.

<script id="gridTemplate" type="text/x-jquery-tmpl">
    <tr class="gridRow">
        <td class="numberingTd">
            var num = 1;
            num = num++

        </td>
        <td class="cellTd">
            <input id="index" name="index" class="numberField" type="text" value="${IndexOrder}" />
        </td>
        <td class="cellTd">${DisplayName}</td>
        <td class="cellTd ">${UrlName} Us</td>
        <td class="cellTd ">${Active}</td>
    </tr>

</script>

<div class="gridDiv">
<table class="gridTable" cellspacing="0" cellpadding="0">
    <tr class="gridTitleRow">
        <td class="numberingTd width36">&nbsp;</td>

        <td class="iconLink width60">Sort Order</td>
        <td class="iconLink widthAuto">Display Name</td>
        <td class="iconLink widthAuto">Url Name</td>
        <td class="iconLink widthAuto">Active</td>
    </tr>
    <span id="mytemp" ></span>
</table>
</div>

Solution

  • I'm not sure what the data object looks like but you need to add a num property to each element. Assuming that data is an array of objects, then something like this should work:

    $.getJSON('/HeaderMenu/GetHeaderGrid', function(data)
    {
        for (var i=0; i<data.length; i++)
        {
            data[i].num = i;
        }
    
        $('#gridTemplate').tmpl(data).appendTo('table.gridTable > tbody');
    });
    

    As @Cory pointed out, you should not have a <span> in the middle of table. Use a <tbody>.

    <table class="gridTable" cellspacing="0" cellpadding="0">
        <tbody>
            <tr class="gridTitleRow">
                <td class="numberingTd width36">&nbsp;</td>
                <td class="iconLink width60">Sort Order</td>
                <td class="iconLink widthAuto">Display Name</td>
                <td class="iconLink widthAuto">Url Name</td>
                <td class="iconLink widthAuto">Active</td>
            </tr>
        </tbody>
    </table>