Home > Enterprise >  paging and search with ajax and partial view in asp.net core
paging and search with ajax and partial view in asp.net core

Time:04-15

I'm using .net core 6 and I have a table that has pagination and if the table page changes, it refreshes the page I want to change the table page without refresh using partialview and Ajax

controller:

        public ActionResult Index(int pageId = 1)
        {
            UsersForAdminViewModel usersForAdminViewModel=_userService.GetAllUsers(pageId);
            return View(usersForAdminViewModel);
        }

userService:

        public UsersForAdminViewModel GetAllUsers(int pageId = 1)
        {
            IQueryable<User> result = _context.Users;
            int take = 1;
            int skip = (pageId - 1) * take;

            UsersForAdminViewModel usersForAdminViewModel = new UsersForAdminViewModel();
            usersForAdminViewModel.CurrentPage = pageId;
            usersForAdminViewModel.PageCount = result.Count() / take;
            usersForAdminViewModel.Users = result.OrderByDescending(d => d.RegisterDate).Skip(skip).Take(take).ToList();
            
            return usersForAdminViewModel;
        }

View:

@model UsersForAdminViewModel

<table >
    <thead>
        <tr>
            <th>Avatar</th>
            <th>UserName</th>
            <th>operation</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Users)
        {
            <tr>
                <td>
                        <img src="/Images/UserAvatars/Thumb/@item.UserAvatar"/>
                </td>

                <td>@item.UserName</td>
                <td>
                    <a asp-action="Details" asp-route-id="@item.UserId" >Details</a>
                </td>
            </tr>
        }
    </tbody>
</table>       
 <ul >

            @for (int i = 1; i <= Model.PageCount; i  )
            {                  
                    <li  aria-controls="dataTables-example" tabindex="0">
                        <a asp-action="Index" asp-route-pageId="@i">@i</a>
                    </li>
            }
        </ul>

Can you tell me how to do this?

Thankyou

CodePudding user response:

Could you show your codes about partialview ?

the script could like below:

<script>
    $(document).ready(function () {
        $("#btRefresh").click(function () {
            $.ajax({
                type: "POST",
                url: "/Test/TestRefresh",
                success: function (data) {
                    $("#TestDiv").html(data);
                },
                error: function (msg) {
                    alert('error:'   msg);
                }
            });
        });
    });

</script>

Controller:

[HttpPost]
        public ActionResult TestRefresh()
        {
            somelogicalcodes
            return PartialView("PartialName", somelist);
        }
  • Related