Add Table Row Using jQuery - MVC 4

10,161

I think there is something wrong with your template code. Please try changing it to

<script type="text/x-jquery-tmpl" id="rowTemplate">
        <tr><td><input type="text" id="txtName_${Counter}" value="" /></td></tr>
    </script>

and then generate html from it like

var obj = {Counter:3};
$("#rowTemplate").tmpl(obj).appendTo("#ProductsTable");

Edit
First I thought you were using jquery template engine and my answer was based on that assumption. you can find how to use templating engine here. Please see that i have also edited the type field in <script type="text/x-jquery-tmpl" .... Import jquery template js file in your code and leave rest of the things as is. It should work then.
Edit 2
Ok that is a different template. Remember you must have unique id for each of your template. That template would look like

<script type="text/x-jquery-tmpl" id="rowTemplate2">
    <tr>
        <td><span class="ProductID">${ProductId}</span></td>
        <td><span class="ProductName">${ProductName}</span></td>
        <td><span class="Price">${Price}</span></td>
        <td>@Html.ActionLink("Edit", "_EditProduct", new { @class = "editLink" })</td>
        <td>@Html.ActionLink("Delete", "_DeleteProduct", new { @class = "editLink" })</td>
    </tr>
</script>

Note how you add placeholders ${Variable} in the templates. Now when you need to use the template, you will need a json object with properties matching the variables used in the template. For example to use above template, I would do something like

var obj2 = {ProductId:2,ProductName:'First Product', Price: 323};//note the properties of json and template vars match.
$("#rowTemplate2").tmpl(obj2).appendTo("#somecontainer");
Share:
10,161
Smiley
Author by

Smiley

Updated on June 30, 2022

Comments

  • Smiley
    Smiley almost 2 years

    I am currently trying to implement an Add functionality to my page. Currently, the add is already functioning but I have to refresh the page in order for the newly added row to appear on the table.

    Please see my codes below:

    This is how I generate my table:

    <table class="webGrid" id="ProductsTable">
    <tr>
        <td><strong><span>ProductID</span></strong></td>
        <td><strong><span>ProductName</span></strong></td>
        <td><strong><span>Price</span></strong></td>
        <td colspan="2"><strong><span>Action</span></strong></td>
    </tr>
    
    @foreach (var item in repository.GetAllProducts(ViewData["BranchCode"].ToString()))
    { 
    <tr>
        <td><span class="ProductID">@item.ProductID</span></td>
        <td><span class="ProductName">@item.ProductName</span></td>
        <td><span class="Price">@item.Price</span></td>
        <td>@Html.ActionLink("Edit", "Edit", new { RecordID = item.RecordID }, new { @class = "editLink" })</td>
        <td>@Html.ActionLink("Delete", "Delete", new { RecordID = item.RecordID }, new { @class = "editLink" })</td>
    </tr>
    }
    

    Currently, the edit and delete are already functioning well. Below is how I do the edit:

    function update(data) {
    if (data.Success == true) {
        var parent = linkObj.closest("tr");
    
        parent.find(".ProductID").html(data.Object.ProductID);
        parent.find(".ProductName").html(data.Object.ProductName);
        parent.find(".Price").html(data.Object.Price);
    }
    else {
        $("#update-message").html(data.ErrorMessage);
        $("#update-message").show();
    }
    

    }

    Now I am trying to implement an add functionality which is almost the same as the edit jquery i am using. I have tried using the .append method unsuccessfully.


    EDIT:

    I have tried using the code below for the add. But it doesn't seem to do anything. Or perhaps I'm doing something wrong:

        function add(data) {
        if (data.Success == true) {
    
            var rowTemplate = $("#rowTemplate").html();
            var tbl = document.getElementById("ProductsTable");
            var counter = $("#ProductsTable tr").length;
            data.Counter = counter;
            $("#ProductsTable").append(applyTemplate(rowTemplate, data));
    
        }
        else {
            $("#update-message").html(data.ErrorMessage);
            $("#update-message").show();
        }
    }
    
    function applyTemplate(template, data) {
        var str = template;
        if ($.isPlainObject(data)) {
            $.each(data, function (index, value) {
                var find = new RegExp("\\$1" + index, "ig");
                str = str.replace(/\$/g, "\$1");
                str = str.replace(find, value);
            });
        }
        return str;
    }
    

    It makes use of a row template such as the following:

    <script type="text/x-template" id="rowTemplate">
            <tr><td><input type="text" id="txtName_$Counter" value="" /></td></tr>
        </script>
    

    I just found this solution online but I can't make it to work. I also tried the code below (i just made up based on the edit jquery I have):

        function add(data) {
        if (data.Success == true) {
            var parent = linkObj.closest("tr");
            parent.find(".ProductID").append(data.Object.ProductID);
            parent.find(".ProductName").append(data.Object.ProductName);
            parent.find(".Price").append(data.Object.Price);
        }
        else {
            $("#update-message").html(data.ErrorMessage);
            $("#update-message").show();
        }
    }
    

    EDIT:

    Right now, this is how my jQuery looks like:

    function add(data) {
        if (data.Success == true) {
            data = { Counter: 3 };
            $("#rowTemplate").tmpl(data).appendTo("#ProductsTable");
            $('#updateDialog').dialog('close');
        }
        else {
            $("#update-message").html(data.ErrorMessage);
            $("#update-message").show();
        }
    }
    

    and this is my template:

    <script type="text/x-template" id="rowTemplate">
        <tr>
            <td><span class="ProductID"></span></td>
            <td><span class="ProductName"></span></td>
            <td><span class="Price"></span></td>
            <td>@Html.ActionLink("Edit", "_EditProduct", new { @class = "editLink" })</td>
            <td>@Html.ActionLink("Delete", "_DeleteProduct", new { @class = "editLink" })</td>
        </tr>
    </script>
    

    Thanks to Sir @Muhammad Adeel Zahid for helping me make the jQuery work to add rows. However, it only adds a new row to my table. What I need now is to make it add the values I have from the data object in the add function of the jQuery.

    I have tried following the tutorial from THIS LINK but I can't seem to make it work. My code is below:

    function add(data) {
        if (data.Success == true) {
            var prod = $.map(data.results, function (obj, index) {
                return {
                    ProductID:  obj.text,
                    ProductName: obj.text,
                    Price: obj.text
                };
            });
    
            prod = { Counter: 3 };
            $("#rowTemplate").tmpl(prod).appendTo("#ProductsTable");
            $('#updateDialog').dialog('close');
        }
        else {
            $("#update-message").html(data.ErrorMessage);
            $("#update-message").show();
        }
    }
    

    Thanks a lot for helping!