Hi nauna,
There is no need to write if else condition to know what is selected.
You just need to pass the filter data with ViewBag.
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
public class CustomerModel
{
public string Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public List<CustomerModel> Customers { get; set; }
}
Controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index(int? page, string city = "", string country = "")
{
ViewBag.Country = country;
ViewBag.City = city;
int pageSize = 5;
int pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
List<CustomerModel> customers = (new NorthwindEntities()).Customers
.Where(x => x.City.Contains(city) && x.Country.Contains(country))
.Select(x => new CustomerModel
{
Id = x.CustomerID,
Name = x.ContactName,
City = x.City,
Country = x.Country
}).ToList();
CustomerModel customer = new CustomerModel();
customer.Customers = customers;
return View(customers.ToPagedList(pageIndex, pageSize));
}
}
@using PagedList
@using PagedList.Mvc
@using _PagedListPager_MVC.Models
@model IPagedList<CustomerModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PagedList Paging MVC</title>
<style>
.ul.pagination {
display: inline-block;
padding: 0;
margin: 0;
}
ul.pagination li {
display: inline;
}
ul.pagination li a {
border: 1px solid #ccc;
color: black;
float: left;
padding: 8px 16px;
text-decoration: none;
transition: background-color .3s;
}
ul.pagination li a.active {
}
ul.pagination li a:hover:not(.active) {
background-color: #ddd;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<table>
<tr>
<td>City</td>
<td><input type="text" name="city" value="@ViewBag.City" /></td>
</tr>
<tr>
<td>Country</td>
<td><input type="text" name="country" value="@ViewBag.Country" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Search" /></td>
</tr>
</table>
<table>
<tr>
<th>@Html.Label("ID")</th>
<th>@Html.Label("Name")</th>
<th>@Html.Label("City")</th>
<th>@Html.Label("Country")</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.City</td>
<td>@item.Country</td>
</tr>
}
</table>
<div class="pagination">
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager(Model, page => Url.Action("Index",
new
{
Country = ViewBag.Country,
City = ViewBag.City,
page
}), PagedListRenderOptions.PageNumbersOnly)
</div>
}
</body>
</html>