Mr.Smithyyy
Mr.Smithyyy

Reputation: 1339

Refreshing partial view in main view table with ajax

I have a piece of my model that needs to be updated every 5 seconds so I stuck it in a partial view but I cannot get it to be placed in the correct spot when it refreshes.

I just cant figure out where to load it, I need it loaded after the headers, like how it originally starts out but unfortunately it loads it above the table or in other obscure spots.

Index

@model IEnumerable<Project.Models.User>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="table-responsive">
                <table class="table">
                    <tr class="table-headers">
                        <th>
                            //Some Info
                        </th>
                        <th>
                            //More Info
                        </th>
                        <th>
                            //Even more Info
                        </th>
                    </tr>
                    @ { Html.RenderPartial("_Index");
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    setInterval(function()
    {
        var url = "@(Html.Raw(Url.Action("Refresh", "Users")))";

        $('.table-headers').after().load(url);
    }, 5000);

_Index

@model IEnumerable<Project.Models.User>

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.Id)</td>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Password)</td>
    </tr>
}

Controller

public ActionResult Refresh()
{
    using DefaultConnection db = new DefaultConnection())
    {
        var model = from t in db.Calls where t.Name == "Joe" select t;

        return PartialView("_Index", model.ToList());
    }
}

Upvotes: 0

Views: 1233

Answers (2)

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

Use thead and tbody like following.

<table class="table">
    <thead>
        <tr class="table-headers">
            <th>
                //Some Info
            </th>
            <th>
                //More Info
            </th>
            <th>
                //Even more Info
             </th>
         </tr>
     </thead>
     <tbody>
            @ { Html.RenderPartial("_Index");
     </tbody> 
</table>

And in your js replace

$('.table-headers').after().load(url); with $('tbody').load(url);

Upvotes: 1

Gene R
Gene R

Reputation: 3744

you can add tbody?:

<table class="table">
    <tr class="table-headers">
        <th>
           //Some Info
        </th>
        <th>
           //More Info
        </th>
        <th>
          //Even more Info
        </th>
    </tr>
    <tbody id="tableBody">
        @Html.Partial("_Index")
    </tbody>
</table>

and use next jquery selector:

$('#tableBody').load(url);

Upvotes: 0

Related Questions