In order to better understand what the code does, I've captured this screencast.
Basically, I have a products page and a user can filter products.
CODE
Here is the Page
action method on my ProductController
:
public ActionResult Page(SearchViewModel search, int page = 1)
{
var viewModel = _productService.GetPagedProducts(search, page);
PopulateDropDownSelectListsForSearchVm(viewModel.Search);
return View(viewModel);
}
That PopulateDropDownSelectListsForSearchVm
is a helper method that sits within the controller.
Here is the implementation of the GetPagedProducts
method on the IProductService
interface:
public ProductPageViewModel GetPagedProducts(SearchViewModel search, int page = 1)
{
int totalNumberOfProducts;
if (HaveSearchTermsChanged(search)) page = 1;
var products = _context.Products.Where(p => p.IsDeleted == search.ShowDeleted).AsQueryable();
if (search.CategoryId != 0) products = products.Where(p => p.CategoryId == search.CategoryId);
if (search.BrandId != 0) products = products.Where(p => p.BrandId == search.BrandId);
if (search.QualityId != 0) products = products.Where(p => p.QualityId == search.QualityId);
if (!string.IsNullOrEmpty(search.SearchTerm))
{
products = products
.Where(p => p.Name == search.SearchTerm.Trim())
.OrderBy(p => p.Name);
totalNumberOfProducts = products.Count();
products = products.Skip(_recordsPerPage * (page - 1)).Take(_recordsPerPage);
}
else
{
products = products.OrderBy(p => p.Name);
totalNumberOfProducts = products.Count();
products = products.Skip(_recordsPerPage * (page - 1)).Take(_recordsPerPage);
}
var productPageVm = new ProductPageViewModel
{
Products = ProductViewModelFactory.BuildListOfProductViewModels(products.ToList()),
Pagination = new PaginationViewModel
{
CurrentPage = page,
RecordsPerPage = _recordsPerPage,
TotalRecords = totalNumberOfProducts
},
Search = search
};
TrackCurrentSearchTerm(productPageVm);
return productPageVm;
}
Readability is really important to me, and right now it just doesn't feel readable. What can I do to improve the overall code, and have it be very readable?
if (HaveSearchTermsChanged(search)) page = 1;
is pointless and you could move your.OrderBy(p => p.Name);
,totalNumberOfProducts = products.Count();
andproducts = products.Skip(_recordsPerPage * (page - 1)).Take(_recordsPerPage);
lines to after theif
block and delete theelse
block \$\endgroup\$if (search.CategoryId != 0)
suggests you not generating them correctly and because the 'label' option should benull
, not0
\$\endgroup\$.AsQueryable()
- it already is \$\endgroup\$