Search code examples
jqueryasp.net-mvcasp.net-mvc-4jquery-ajaxq

append data two time to the table when get data from controller(jquery ajax)


recently i encountered with the confused proplem.

i want to lazy loading according to the bellow link: ASP.NET MVC Infinite Scrolling Jquery

when run project and used a feature that implemented . everything is working properly but jquery not . it append my data two time see image: pay attention to first field which is a number

every thing is ok (firebug illustrate correct data) but what was happen there.

my jquery code is :

var page = 1;
var scrollHandler = function () {
    if (($(window).scrollTop() == $(document).height() - $(window).height()))
        loadMoreToInfiniteScrollTable();

}

function loadMoreToInfiniteScrollTable() {
    page++;
    $.ajax({
        type: 'GET',
        url: dataUrl,
        data: "p=" + page,
        success: function (data) {
            if (data) {
                $('tbody').append( data );
                
        }
        }
    });
    
}

calling method

    <script type="text/javascript">
        var dataUrl = '@Url.RouteUrl("UserInfo")';
        $(window).scroll(scrollHandler);
    </script>

controller action methods : its populate view for once

    public List<inf> lst;
    public ActionResult ExpressionDetail()
    {
        var data = lst.Where(f=>f.id>0&&f.id<lenght).OrderBy(i=>i.id);

        return View(data);
    }

and the partial view for page sepration:

    [HttpGet]
    public ActionResult _TableData(int? p=0)
    {
        int firstfrom = p ?? 1;
        int endfrom = (firstfrom > 1 ? (firstfrom - 1) * lenght : 0);

        var g= lst.OrderBy(i=>i.id).Skip(endfrom-1).Take(lenght).AsEnumerable();

        return PartialView(g);
    }

route config:

routes.MapRoute("UserInfo", "",new {Controller= "Default", Action= "_TableData" });

const lenght:

public const int lenght = 15;

partialview:

@model IEnumerable<testable.Models.inf>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.id)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.name)
    </td>

</tr>

}

and main view:

@model IEnumerable<testable.Models.inf>
<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ExpressionDetail</title>
</head>
<body>

<table class="table">
    <tr>
        <th>
            Id
        </th>
        <th>
            name
        </th>
    </tr>
@Html.Partial("_TableData", Model)
    <tbody>

    </tbody>

</table>

</body>
</html>

inf model

public class inf
{
    public int id { get; set; }
    public string name { get; set; }
}

Solution

  • my problems solved by only remove one of the tbody so that behind the sense generated two tbody so by avoid <tbody></tbody> explisitely our problems solved and its working properly.

    tnx and congratulation of MR Stephen Muecke