我想按类别显示项目。我使用 linq 并且一切正常,除了我无法显示所有项目,无论类别。可能是路由问题,因为我已经问过有关我使用的 linq 表达式的问题,应该没问题。无论如何,这是我的代码:
public ViewResult Content(string category, int page = 1)
{
var model = new StoreContentViewModel
{
Items = _itemsRepository.GetItems()
.Where(i => i.Product.Category == null ||
i.Product.Category != null && i.Product.Category == category)
.OrderBy(i => i.ItemId)
.Skip((page - 1) * PageSize)
.Take(PageSize)
.Select(i => i),
}
}
RegisterRouts 方法的内容:
// without categories
routes.MapRoute(
null,
"Store/Content/Page{page}",
new { controller = "Store", action = "Content", category = (string)null},
new { page = @"\d+" });
// with categories
routes.MapRoute(
null,
"Store/Content/{category}/Page{page}",
new { controller = "Store", action = "Content" },
new { page = @"\d+" });
// Default route
routes.MapRoute(
null,
"{controller}/{action}",
new { controller = "Home", action = "Index"});
我对“有和没有类别”溃败的顺序感到困惑。
事情是当我输入网址时:
~/Store/Content
或者:
~/Store/Content/Page1 // or Page2
项目不显示。但如果我输入:
~/Store/Content/Man's-Shoes/Page1
显示与“男鞋”类别相关的项目。
那么,这个问题与溃败或mabby有关吗?还有另一个问题吗?
ps过去两天我一直在处理这个问题,所以任何帮助都是合适的。
编辑:
还有这个单元测试失败了。大概是写的不好。也检查一下。
在我的模型中,我有“包含”产品和运输实体的 Items 实体:
[TestMethod]
public void Can_Filter_Content()
{
//Arrange
private Mock<IItemsRepository> _itemsMock = new Mock<IItemsRepository>();
private Mock<IProductRepository> _productsMock = new Mock<IProductRepository>();
private Mock<IShippingRepository> _shippingMock = new Mock<IShippingRepository>();
_itemsMock.Setup(i => i.GetItems()).Returns(new[]
{
new Item { ItemId = 1, ProductId = 1, ShippingId = 1},
new Item { ItemId = 2, ProductId = 2, ShippingId = 2},
new Item { ItemId = 3, ProductId = 3, ShippingId = 3},
new Item { ItemId = 4, ProductId = 4, ShippingId = 4}
});
_productsMock.Setup(p => p.GetProducts()).Returns(new[]
{
new Product { ProductId = 1, Category = "shoes"},
new Product { ProductId = 2, Category = "shoes"},
new Product { ProductId = 3, Category = "superShoes"},
new Product { ProductId = 4, Category = "shoes"}
});
var controller = new StoreController(_itemsMock.Object,
_productsMock.Object, _shippingMock.Object) {PageSize = 2};
// Act
Item[] result = ((StoreContentViewModel) controller.Content(null).Model).Items.ToArray();
ViewResult viewResult = controller.Content(null);
// Assert
Assert.IsTrue(result[0].ItemId == 1 && result[1].ItemId == 2);
Assert.AreEqual(result.Length, 2);
Assert.AreEqual("", viewResult.ViewName);
}
马比这有帮助