Reputation: 31
So I have a ASP.NET MVC 5 Based shopping cart project and one of the requirements is to show 8 products per page. I have 21 products in total. This is how I'm showing them at the moment:
public ActionResult Index()
{
String SQL = "SELECT ProductId, Products.CategoryId AS CategoryId, Name, ImageFileName, UnitCost"
+ ", SUBSTRING(Description, 1, 100) + '...' AS Description, isDownload, DownloadFileName "
+ "FROM Products INNER JOIN Categories ON Products.CategoryId = Categories.CategoryId ";
String CategoryName = Request.QueryString.Get("CategoryName");
if (CategoryName != null)
{
if (CategoryName.Length > 20 || CategoryName.IndexOf("'") > -1 || CategoryName.IndexOf("#") > -1)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SQL += "WHERE CategoryName = @p0";
ViewBag.CategoryName = CategoryName;
}
var products = db.Products.SqlQuery(SQL, CategoryName);
return View(products.ToList());
}
This is the cshtml:
@model IEnumerable<PiClub.Models.Product>
@{
ViewBag.Title = "Shop";
}
@Styles.Render("~/Content/Site.css")
<h2>Shop</h2>
<table class="table">
<tr>
<th>
Name
</th>
<th>
Image
</th>
<th>
Price
</th>
<th>
Description
</th>
<th>
Category
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@item.Name
</td>
<td>
<img src="/Images/@item.ImageFileName" style="width:200px" />
</td>
<td style="text-align:right">
@item.UnitCost
</td>
<td>
@item.Description
</td>
<td>
@item.Category.CategoryName
</td>
<td>
<input type="button" value="Add to Cart" onclick="NavCart('@item.ProductId')" />
</td>
<td>
<input type="button" value="Details" onclick="NavDetails('@item.ProductId')" />
</td>
</tr>
}
</table>
<script type="text/javascript">
function NavDetails(ProductId) {
window.location.replace("/Shop/Details?PrdouctId=" + ProductId);
}
function NavCart(ProductId) {
window.location.replace("/OrderDetails/ShoppingCart?ProductId=" + ProductId);
}
</script>
How do I go about doing this?
Upvotes: 3
Views: 551
Reputation: 670
Put two parameters at your method, which will represent the page number and items per page:
public ActionResult Index(int pageNumber, int itemsPerPage)
Then add Skip and Take where you grab data from database:
var products = db.Products.SqlQuery(SQL, CategoryName)
.Skip(pageNumber * itemsPerPage)
.Take(itemsPerPage);
Then send parameters via url:
http://your-url/ControllerName/Index?pageNumber=2&itemsNumber=8
Upvotes: 3
Reputation: 9463
You can use LINQ Skip
and Take
to implement paging.
const int itemsPerPage = 8;
int currentPage = 0; // parameter to the passed; first page has index 0
var result = db.Products.SqlQuery(SQL, CategoryName)
.Skip(currentPage * itemsPerPage)
.Take(itemsPerPage);
Upvotes: 1