我正在为手机建立在线目录,我有两个控制器,一个用于手机目录,第二个用于手机详细信息。有了目录,一切都很好,现在我的目标是在点击目录中的手机名称或照片后查看手机详细信息。我认为有了手机的id,解决这个任务更容易,而且我使用了存储库模式。
此目录的控制器:
public class PhonesCatalog : Controller
{
private readonly IPhoneRepository _repository;
public int PageSize = 6;
public PhonesCatalog(IPhoneRepository repository)
{
_repository = repository;
}
[HttpGet]
public IActionResult Catalog(int productPage = 1)
=> View(new ProductsListViewModel
{
Phones = _repository.Phones
.OrderBy(x => x.PhoneId)
.Skip((productPage -1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = productPage,
ItemsPrePage = PageSize,
TotalItems = _repository.Phones.Count()
}
});
}
存储库模式:
public interface IPhoneRepository
{
IQueryable<Phone> Phones { get; }
Phone GetPhoneById(int id);
}
public class EfMobileStoreRepository : IPhoneRepository
{
private readonly MobileStoreCatalogContext _context;
public EfMobileStoreRepository(MobileStoreCatalogContext context)
{
_context = context;
}
public IQueryable<Phone> Phones => _context.Phones;
public Phone GetPhoneById(int id) => _context.Phones
.FirstOrDefault(p => p.PhoneId == id);
}
这是电话详细控制器和视图:
public class PhonesDetails : Controller
{
private readonly IPhoneRepository _repository;
public PhonesDetails(IPhoneRepository repository)
{
_repository = repository;
}
[HttpGet]
public IActionResult Details(int id)
{
return View(_repository.GetPhoneById(id));
}
}
@model Mobile_Store_Catalog_wandio.Models.Phone
<h4>Phone Details</h4>
<div class="row">
<p>@Model.PhoneName</p>
<p>@Model.Manufactor</p>
<p>@Model.OperationSystem</p>
<p>@Model.Processor</p>
<p>@Model.Memory</p>
<p>@Model.ScreenResolution</p>
<p>@Model.Size</p>
<p>@Model.Wight</p>
</div>
此处目录视图:
@model ProductsListViewModel
<h1>Phone Catalog</h1>
<div class="container-fluid">
<div class="container-fluid">
<div class="row">
<div class="col-md-3 btn-group-vertical text-center">
Filter
Search
</div>
<div class=" row col-md-9">
@foreach (var p in Model.Phones)
{
<div class=" col-md-4 border border-dark">
<a href="@Url.Action("Details", "PhonesDetails")">
<img class="img-fluid" src="/Images/@p.ImageName"/>
</a>
<p class="text-center container">@p.PhoneName</p>
<p class="text-white text-center bg-success">@p.Price.ToString("C2")</p>
</div>
}
</div>
</div>
</div>
</div>
<div class="row">
<div page-model="@Model.PagingInfo" page-action="Catalog" page-classes-enabled="true"
page-class="btn" page-class-normal="btn-outline-dark"
page-class-selected="btn-primary" class="btn-group-toggle m-1 al">
</div>
</div>
这是ProductViewList代码:
public class ProductsListViewModel
{
public IEnumerable<Phone> Phones { get; set; }
public PagingInfo PagingInfo { get; set; }
}
问题是,当我点击手机图像时,它只获取手机的第一个id并返回其详细信息,点击哪个图像并不重要,但我需要按id返回详细信息,而不仅仅是第一个id的手机详细信息。
我在这里做错了什么,有人能帮我吗?
您可以这样更改代码:
<a asp-controller="PhonesDetails" asp-action="Details" asp-route-id="@p.Id">
<img class="img-fluid" src="/Images/@p.ImageName"/></a>