I am implementing paging in asp.net core mvc 6.0
here is my code on controller
using X.PagedList;
public IActionResult Index(int? page)
{
Employee emp = new Employee();
emp.EmpModel = _repository.GetAllEmployee().ToPagedList(page ?? 1,3);
return View(emp);
}
here is code on view
@model IPagedList
@using X.PagedList.Mvc.Core;
@using X.PagedList;
@using X.PagedList.Web.Common;
@{
Layout = null;
}
@using (Html.BeginForm("Index","Home",FormMethod.Post,new{@class="form-horizontal"}))
{
@Html.LabelFor(model => model.First().Department, new {@class="control-label col-sm-2"})
@Html.DropDownList("Department",new List
{
new SelectListItem { Text = "IT", Value = "IT"},
new SelectListItem { Text = "HR", Value = "HR"},
new SelectListItem { Text = "Payroll", Value = "Payroll"}
},"Select Department",new{@class="form-control"})
@Html.ValidationMessageFor(model => model.First().Department, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.First().EmpName, new { @class = "control-label col-sm-2" })
@Html.TextBoxFor(model =>model.First().EmpName, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.First().EmpName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.First().EmailId, new { @class = "control-label col-sm-2" })
@Html.TextBoxFor(model => model.First().EmailId, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.First().EmailId, "", new { @class = "text-danger" })
}
@{
if(Model.First().EmpModel != null && Model.First().EmpModel.Count > 0)
{
| Name | Department | Edit | Delete | |
|---|---|---|---|---|
| @emp.EmpName | @emp.EmailId | @emp.Department | @Html.ActionLink("Edit", "Edit", new { id = emp.Id },new { @class = "btn btn-primary" }) |
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), new PagedListRenderOptions { DisplayLinkToFirstPage = PagedListDisplayMode.Always, DisplayLinkToLastPage = PagedListDisplayMode.Always })
}
}
Please let me know what needs to be done
i am stuck on this

Tuhin PaulPosted Mar 10, 2024, 4:58 PM
To address the issue with displaying the name and email ID of the first record in the textboxes, you should modify the view to correctly bind each textbox to the properties of the corresponding employee object within the loop. Instead of using Model.First().EmpName and Model.First().EmailId, you should directly bind the textboxes to the properties of the current emp object within the loop. Here's how you can improve the code:
Changes made:
Jignesh KumarPosted Mar 4, 2024, 3:37 AM
Hello Aniket,
Please refer this article which will help you out to solve your issue,
https://dev.to/masanori_msl/asp-net-core-using-x-pagedlist-2ek9
Aniket NarvankarPosted Mar 4, 2024, 2:16 AM
Hi Prasad
Here is the Data Access Layer code
using Asp.NetCoreApp.Model;
using System.Data;
using System.Data.SqlClient;
namespace Asp.NetCoreApp.DAL _logger; logger)
{
public class DataAccessLayer
{
private string _connectionstring;
private SqlConnection _con;
private ILogger
public DataAccessLayer(string connectionstring, ILogger
{
_connectionstring = connectionstring;
_con = new SqlConnection(_connectionstring);
_logger = logger;
}
List emp = new List(); GetAllEmployee()
public List
{
_logger.LogInformation("Fetching All Employee Details");
try
{
using(SqlCommand cmd= new SqlCommand("insert_update_delete_employee",_con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Para","Get");
if (_con.State.Equals(ConnectionState.Closed))
_con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee employee = new Employee();
employee.Id = Convert.ToInt32(dr["Id"]);
employee.EmpName = Convert.ToString(dr["EmpName"]);
employee.EmailId = Convert.ToString(dr["Email"]);
employee.Department = Convert.ToString(dr["Department"]);
emp.Add(employee);
}
_con.Close();
_logger.LogInformation("Fetched All Employee Details,total employees are : "+emp.Count);
}
}
catch(Exception ex)
{
_logger.LogError(ex.Message, "An error occurred while getting all employees.");
}
return emp;
}
SQL Repository Class code
using Asp.NetCoreApp.DAL;
using Asp.NetCoreApp.Model;
namespace Asp.NetCoreApp.Repository GetAllEmployee()
{
public class SQLRepository : IRepository
{
private readonly DataAccessLayer _dal;
public SQLRepository(DataAccessLayer dal)
{
_dal = dal;
}
public List
{
return _dal.GetAllEmployee();
}
}
interface IRepository Code
using Asp.NetCoreApp.Model;
namespace Asp.NetCoreApp.Repository
GetAllEmployee();
{
public interface IRepository
{
List
}
}
statup.cs code
using Asp.NetCoreApp.DAL;
using Asp.NetCoreApp.Repository;
using NLog;
namespace Asp.NetCoreApp(provider => new DataAccessLayer(connectionString, provider.GetRequiredService>()));(); logger)
{
public class Startup
{
public IConfiguration _configuration { get; }
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
services.AddMvc(options => options.EnableEndpointRouting = false);
services.AddScoped
services.AddScoped
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger
{
if (!env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.Use(async (context, next) =>
{
// Get the NLog logger
var logger = NLog.LogManager.Setup().LoadConfigurationFromFile("wwwroot/nlog.config").GetCurrentClassLogger();
// Log the request
logger.Info("HTTP {method} {url}", context.Request.Method, context.Request.Path);
// Call the next middleware in the pipeline
await next.Invoke();
});
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
}
}
}
program.cs code
using Asp.NetCoreApp;
using NLog.Web;
public class Program();
{
public static void Main(string[] args)
{
CreateBuilder(args).Build().Run();
}
public static IHostBuilder CreateBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup
webBuilder.UseNLog();
});
}
Employee.cs code
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Asp.NetCoreApp.Model
{
public class Employee
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage="Employee Name is Required")]
[StringLength(50,ErrorMessage ="Name must be Upto 50 characters only")]
[DisplayName("Enter Name")]
public string EmpName { get; set; }
[Required(ErrorMessage = "EmailId is Required")]
[RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", ErrorMessage = "Invalid Email Format")]
[DisplayName("Enter Email Id")]
public string EmailId { get; set; }
[Required(ErrorMessage = "Department Name is Required")]
? EmpModel { get; set; }
[DisplayName("Select Department")]
public string Department { get; set; }
public int IsActive { get; set; }
public List
}
}
This is homecontroller code
using Asp.NetCoreApp.Repository;
using Microsoft.AspNetCore.Mvc;
using X.PagedList;
namespace Asp.NetCoreApp.Controllers
{
public class HomeController : Controller
{
private IRepository _repository;
public HomeController(IRepository repository)
{
_repository = repository;
}
public IActionResult Index(int? page)
{
Employee emp = new Employee();
emp.EmpModel = _repository.GetAllEmployee();
return View(emp.EmpModel.ToPagedList(page ?? 1,3));
}
}
@model IPagedList
@using X.PagedList.Mvc.Core;
@using X.PagedList;
@using X.PagedList.Web.Common;
@{
Layout = null;
}
@using (Html.BeginForm("Index","Home",FormMethod.Post,new{@class="form-horizontal"}))
{
@Html.LabelFor(model => model.First().Department, new {@class="control-label col-sm-2"})
@Html.DropDownList("Department",new List
{
new SelectListItem { Text = "IT", Value = "IT"},
new SelectListItem { Text = "HR", Value = "HR"},
new SelectListItem { Text = "Payroll", Value = "Payroll"}
},"Select Department",new{@class="form-control"})
@Html.ValidationMessageFor(model => model.First().Department, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.First().EmpName, new { @class = "control-label col-sm-2" })
@Html.TextBoxFor(model => model.First().EmpName,new{ @class = "form-control" })
@Html.ValidationMessageFor(model => model.First().EmpName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.First().EmailId, new { @class = "control-label col-sm-2" })
@Html.TextBoxFor(model => model.First().EmailId, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.First().EmailId, "", new { @class = "text-danger" })
}
@{
if(Model != null && Model.Count > 0)
{
@foreach (var emp in Model)
{
using (Html.BeginForm("Delete","Home",new { id = emp.Id },FormMethod.Post))
{
@Html.ActionLink("Edit", "Edit", new { id = emp.Id },new { @class = "btn btn-primary" })
}
}
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), new PagedListRenderOptions { DisplayLinkToFirstPage = PagedListDisplayMode.Always, DisplayLinkToLastPage = PagedListDisplayMode.Always })
}
}
The issue was with Model.EmpModel was null so grid was not loading. changed if(Model.EmpModel != null && Model.EmpModel.Count > 0) to if(Model != null && Model.Count > 0) it started working.
foreach also changed from @foreach (var emp in Model.EmpModel) to @foreach (var emp in Model)
but now new issue is there
the name textbox and email id textbox are displaying the name and email id of first record. as Model.First().EmpName is used. how to resolve this. what can be the alternative. Please guide me.
Prasad RaveendranPosted Mar 3, 2024, 6:48 PM
I have noticed that you are using the X.PagedList library for pagination in your ASP.NET Core application. At a glance there are no issues with your code. However, I notice that you are using a form for each row in the table, which might interfere with the proper functioning of the pagination.
Here are a few suggestions to address the issue:
Move the Form outside the loop: Instead of having a form for each row, consider moving the form outside the loop. This ensures that the pagination links are not inside individual forms.
Move the PagedListPager outside the loop: Ensure that the PagedListPager is not inside the loop. Place it after the closing
tag.By making these adjustments, you should have a more standard structure for your HTML, which may help in resolving any issues with pagination. If the problem persists, please provide more details about the specific issue or error you are encountering.