在.net核心MVC中使用TagHelper创建类别列表

问题描述

我想学习.net核心-我正在学习一本书 Pro ASP.NET Core MVC 2 Adam Freeman

我在第9章中创建了在线商店。 我正在尝试创建类别列表。 我想基于视图模型类重写此组件,并使用TagHelper。

我的问题:

  • 我所做的全部正确吗?
  • 我如何提供有关 活动类别(“突出显示”)?
  • 为什么链接到活动 按以下方案创建的类别:href =“ / Chess / Page1,但是 以这种方式转到非活动类别:href =“ / Page1?Category = Water%20sports”?

最初,视图是这样创建的:

@model IEnumerable<string>

<a class="btn btn-block btn-secondary"
   asp-action="List"
   asp-controller="Product"
   asp-route-category="">
    Strona główna
</a>

@foreach (string category in Model)
{
    <a class="btn btn-block
        @(category == ViewBag.SelectedCategory ? "btn-primary": "btn-secondary")"
       asp-action="List"
       asp-controller="Product"
       asp-route-category="@category"
       asp-route-productPage="1">
        @category
    </a>
}

我的更改:

  1. 我创建了CategoryListviewmodel视图模型:
 public class CategoryListviewmodel
    {
        public IEnumerable<Category> Categories { get; set; }
        public CategoringInfo CategoringInfo { get; set; }
    }
  1. 和帮助程序类CategoringInfo
 public class CategoringInfo
    {
        public int TotalCategories;
        public List<Category> Categories { get; internal set; }
        public string CurrentCategory { get; internal set; }
    }
  1. 然后,我更改了组件本身(在NavigationMenuViewComponent文件中)的视图创建方法(实际上传递给了模型视图)
  public class NavigationMenuViewComponent : ViewComponent
    {
        private IProductRepository repository;

        public NavigationMenuViewComponent(IProductRepository repo)
        {
            repository = repo;
        }

        public IViewComponentResult Invoke()
        {
            ViewBag.SelectedCategory = RouteData?.Values["category"];
            IEnumerable<string> categories = repository.Products
                  .Select(x => x.Category)
                  .distinct()
                  .OrderBy(x => x);

            List<Category> cat = new List<Category>();
            foreach (string c in categories)
                cat.Add(new Category { Name = c });

            CategoringInfo ci = new CategoringInfo
            {
                TotalCategories = categories.Count(),Categories = cat
            };

            CategoryListviewmodel clvm = new CategoryListviewmodel
            {
                Categories = cat,CategoringInfo = ci
            };

            return View(clvm);
        }
    }
  1. 最后,我改变了看法:
@model CategoryListviewmodel

    <div category-model="@Model.CategoringInfo" category-action="List"
         category-classes-enabled="true" category-class="btn btn-block" category-class-normal="btn-secondary"
         category-class-selected="btn-secondary">
    </div>

我将源放在github上:https://github.com/TomaszFilipek/PublicSportStore 在master分支中有本书的一个版本,是我在CategoryNavigation分支中更改后的版本。

预先感谢您的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)