Reputation: 69
I'm developing an online shop website which will contain a default set of functionalities as products pages, product categories, commentaries, personal cart etc. This is the first time I'm doing such project and during implementation of features I'm faced some difficulties with handling different exceptions in Views. Hence I would like to understand best practices of designing good code in Views which would be extendable in the future.
Let's say I have a Shop controller with Category action that displays list of products related to the category we are in. In corresponding category View I need to loop over product list and depending on user's role and authorization (admin, user, guest) hide some inactive products. The way I'm doing it now is something like this (code is simplified):
@model ProductList
@foreach (var i in Model) {
@if (i.Product.Active || UserManager.IsInRole(User, "Admin")) {
<div class="product">
@if (i.Data.Path == null) {
<img src="placeholder.png">
}
else {
<img src="@i.Data.Path">
}
...
</div>
}
}
While it looks intuitively clear, I realized that sooner or later this will become very messy once I add few more conditional branching. So my question: is there any other approach to handle such exceptions branching? I've heard about custom HtmlTagHelpers (which could make code more HTML looking while keeping some conditional logic behind), but it looks that it will take more time to explicitly write logic for each exception.
Thank you in advance!
Upvotes: 0
Views: 257
Reputation: 5729
The views must not contain data logic, all your data logic must be in the backend, and for your case, put the logic where you do query for the products. e.g.:
public async Task<IActionResult> Index()
{
var query = UserManger.IsInRole(User, "Admins")
? _context.Set<Products>()
: _context.Set<Products>().Where(x => x.IsActive == false);
Products = await query.Skip(/*number*/).Take(/*quantity*/).ToListAsync();
// ...
}
As mentioned in the comment, view logic can take place inside the view e.g.:
@if(!Product.IsInStock)
{
<span class="text-danger">Not Available</span>
}
Upvotes: 2