嵌套类别选择框

时间:2018-11-11 11:35:18

标签: asp.net-core asp.net-core-mvc asp.net-core-2.0

public class Category
{
    [Key]
    [Display(Name = "ID")]
    public int Id { get; set; }

    [Display(Name = "Parent Category")]
    public int? ParentId { get; set; }

    [Required]
    [Display(Name = "Category Name")]
    public string Name { get; set; }

    [Required]
    [Range(0, int.MaxValue)]
    [Display(Name = "Display Order")]
    public int DisplayOrder { get; set; }

    [Required]
    [Display(Name = "Active")]
    public bool IsActive { get; set; }

    [Display(Name = "Created At")]
    public DateTime CreatedAt { get; set; }

    [Display(Name = "Updated At")]
    public DateTime UpdatedAt { get; set; }

    [ForeignKey("ParentId")]
    public virtual Category Parent { get; set; }
}

这是我的类别模态。我希望将此模式嵌套在这样的select标记中:

车辆
-汽车
-宝马
-奥迪
房地产
-住宅
-出售
等等...

我在项目中也使用了存储库模式。所有必需的文件都在下面依次列出。

接口:

public interface IRepository<T> where T : class
{
    IEnumerable<T> List();
    T Find(int? id);
    T Find(Func<T, bool> predicate);
    void Create(T entity);
    void Update(T entity);
    void Delete(T entity);
    int Count(Func<T, bool> predicate);
    void Add(T entity);
    void Save();
}

public interface ICategoryRepository : IRepository<Category>
{
    IEnumerable<Category> ListParentCategories();
}

在相关视图中:

@model GoldenStore.Models.ViewModels.CategoryViewModel
@using GoldenStore.Extensions

<select asp-for="Category.ParentId" asp-items="Model.Categories.ToSeceltListItem(Model.Category.Id)" class="input-select">
     <option value="">Main Category</option>
</select>

在扩展文件夹中:

public static class ReflectionExtension
{
    public static string GetPropertyValue<T>(this T item, string propertyName)
    {
        return item.GetType().GetProperty(propertyName).GetValue(item, null).ToString();
    }
}

public static class IEnumerableExtension
{
    public static IEnumerable<SelectListItem> ToSeceltListItem<T>(this IEnumerable<T> items, int selectedValue)
    {
        return from item in items
               select new SelectListItem
               {
                   Text = item.GetPropertyValue("Name"),
                   Value = item.GetPropertyValue("Id"),
                   Selected = item.GetPropertyValue("Id").Equals(selectedValue.ToString())
               };
    }
}

CategoryViewModel:

public class CategoryViewModel
{
    public Category Category { get; set; }
    public IEnumerable<Category> Categories { get; set; }
}

因此,对于这样的嵌套类别,我该怎么办:

车辆
-汽车
-宝马
-奥迪
房地产
-住宅
-出售
等等...

0 个答案:

没有答案