Is there a way to sort this in a query?
View models, of course:
public class CategoryViewModel { public string Title { get; set; } public IEnumerable<ProductViewModel> Products { get; set; } } public class ProductViewModel { public string Description { get; set; } }
and in the action of your controller you need to populate this view model:
public ActionResult Index() { var categories = (from category in context.Categories orderby category.SortOrder ascending select new CategoryViewModel { Title = category.Title, Products = category .Products .OrderBy(p => p.SortOrder) .Select(p => new ProductViewModel { Description = p.Description }) }).ToList(); ).ToList(); return View(categories); }
and in the Index.cshtml you can get rid of ugly loops and use display templates:
@model IEnumerable<CategoryViewModel> <ul> @Html.DisplayForModel() </ul>
and inside the display template for the category ( ~/Views/Shared/CategoryViewModel.cshtml )
@model CategoryViewModel <li> @Html.DisplayFor(x => x.Title) <ul> @Html.DisplayFor(x => x.Products) </ul> </li>
and inside the display template for the product ( ~/Views/Shared/ProductViewModel.cshtml )
@model ProductViewModel <li> @Html.DisplayFor(x => x.Description) </li>
As an additional enhancement to the action of the controller, you can use AutoMapper to map between your domain models (EF objects) and your view models, which should be passed to the view.
Darin Dimitrov
source share