How to do Sorting and paging in ASP.NET MVC C# with a built int SQL database

95 Views Asked by At

Okay so I am a beginner with ASP.NET and I am trying to do a small project where I create a customer tracking website. I have done everything to be able to create my tables, add, edit, details and delete entries and I have gotten pretty much to the point where I am happy. My next step is to add sorting to my entries and to be able to add paging. I want to be able to make it on the website, that only 10 entries are displayed at a time. I have never done this before and googling and AI are just confusing me, as well as I have never used JSON before and adding that into my code broke everything and I wasn't sure how to fix it/

This is my code for my Index.cshtml: that gives me the display of each entry as well as the edit, details and delete buttons. I'm not sure if the paging and sorting will even go into this view code or if I have to create another model/controller and if it does go in here, I am not sure where.

@model IEnumerable<ArksoftTestDev.Models.Customer>

@{
    ViewBag.Title = "Index";
}

<body style="background-color: #002f3c ">
<h1 style="color: #b5ff1e; ">Index</h1>

<h4 >
    @Html.ActionLink("Create New", "Create")
</h4>
<table class="table" >
    <tr>
        <th style="color: forestgreen; ">
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th style="color: forestgreen; ">
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th style="color: forestgreen; ">
            @Html.DisplayNameFor(model => model.TelephoneNumber)
        </th>
        <th style="color: forestgreen; ">
            @Html.DisplayNameFor(model => model.ContactPersonName)
        </th>
        <th style="color: forestgreen; ">
            @Html.DisplayNameFor(model => model.ContactPersonEmail)
        </th>
        <th style="color: forestgreen; ">
            @Html.DisplayNameFor(model => model.VATNumber)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td style="color: whitesmoke; ">
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td style="color: whitesmoke; ">
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td style="color: whitesmoke; ">
            @Html.DisplayFor(modelItem => item.TelephoneNumber)
        </td>
        <td style="color: whitesmoke; ">
            @Html.DisplayFor(modelItem => item.ContactPersonName)
        </td>
        <td style="color: whitesmoke; ">
            @Html.DisplayFor(modelItem => item.ContactPersonEmail)
        </td>
        <td style="color: whitesmoke; ">
            @Html.DisplayFor(modelItem => item.VATNumber)
        </td>
        <td style="color: whitesmoke; ">
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>
    </body>

I have tried using JQueries and LINQ, but tutorials were not helping and I am now very confused and frustrated that I cannot get this to work. Please can someone explain and help me in a "explaining for dummies" sort of way!

1

There are 1 best solutions below

1
Jaydev Kanzariya On
   create this type viewmodel and in this viewmodel category is main model that is keeped in database
    public class CategoryIndexVM
{
    public IEnumerable<Category> Categories { get; set; }
    public string NameSortOrder { get; set; }
    public int PageSize { get; set; }
    public int CurrentPage { get; set; }
    public int TotalPages { get; set; }
    public string Term { get; set; }
    public string OrderBy { get; set; }
}

   Add this code in controller index method
public IActionResult Index(string term = "", string orderBy = "", int currentPage = 1)
{

    // expressions that could cause an exception

    ViewData["CurrentFilter"] = term;
    term = string.IsNullOrEmpty(term) ? "" : term.ToLower();



    CategoryIndexVM categoryIndexVM = new CategoryIndexVM();
    categoryIndexVM.NameSortOrder = string.IsNullOrEmpty(orderBy) ? "Name_desc" : "";
    var categories = (from data in _unitOfWork.Category.GetAll().ToList()
                      where term == "" ||
                         data.Name.ToLower().
                         Contains(term)


                      select new Category
                      {
                          Id = data.Id,
                          Name = data.Name,
                          Description = data.Description,
                          IsActive = data.IsActive

                      });
    switch (orderBy)
    {
        case "Name_desc":
            categories = categories.OrderByDescending(a => a.Name);
            break;

        default:
            categories = categories.OrderBy(a => a.Name);
            break;
    }
    int totalRecords = categories.Count();
    int pageSize = 5;
    int totalPages = (int)Math.Ceiling(totalRecords / (double)pageSize);
    categories = categories.Skip((currentPage - 1) * pageSize).Take(pageSize);
    categoryIndexVM.Categories = categories;
    categoryIndexVM.CurrentPage = currentPage;
    categoryIndexVM.TotalPages = totalPages;
    categoryIndexVM.Term = term;
    categoryIndexVM.PageSize = pageSize;
    categoryIndexVM.OrderBy = orderBy;
    return View(categoryIndexVM);
}
   Add this code in view For pagination design
<nav aria-label="Page navigation example">
    <ul class="pagination">
        @if (Model.CurrentPage > 1)
        {
            <li class="page-item">
                <a class="page-link" href="/Admin/Category/[email protected]&[email protected]&currentPage=@(Model.CurrentPage-1)" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
        }
        @for (int i = 1; i <= Model.TotalPages; i++)
        {
            if (i == Model.CurrentPage)
            {
                <li class="page-item"><a class="page-link active" style="background-color:rgb(69, 206, 244)" href="/Admin/Category/[email protected]&[email protected]&currentPage=@i"> @i</a></li>
            }
            else
            {
                <li class="page-item"><a class="page-link" style="background-color:floralwhite" href="/Admin/Category/[email protected]&[email protected]&currentPage=@i"> @i</a></li>
            }
        }
        @if (Model.CurrentPage < Model.TotalPages)
        {
            <li class="page-item">
                <a class="page-link" href="/Admin/Category/[email protected]&[email protected]&currentPage=@(Model.CurrentPage+1)" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        }
    </ul>
</nav>