2017-04-14 90 views
3

所以我有一个基于ASP.NET MVC 5的购物车项目,其中一个要求是每页显示8个产品。我共有21种产品。这就是我如何展示他们的时刻:如何在单独的页面中显示我的产品?

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()); 
    } 

这是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> 

我如何去这样做呢?

+0

理想情况下,您应该使用某种类似datatable的分页格来显示产品。 – jjj

+0

我最终做的是遵循本教程:https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering -and-寻呼与 - 的实体框架功能于一个-ASP净MVC-应用 – meiji

回答

1

您可以使用LINQ SkipTake来实现分页。

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); 
3

把两个参数在你的方法,这将代表每页的页码和项目:

public ActionResult Index(int pageNumber, int itemsPerPage) 

然后加入跳过,并采取在那里你从数据库获取数据:

var products = db.Products.SqlQuery(SQL, CategoryName) 
          .Skip(pageNumber * itemsPerPage) 
          .Take(itemsPerPage); 

然后通过url发送参数:

http://your-url/ControllerName/Index?pageNumber=2&itemsNumber=8

相关问题