繁体   English   中英

@ Html.DropdownList将类别>>子类别>>子类别显示为文本值

[英]@Html.DropdownList to show Category >> Subcategory >> Subcategory as text value

我有一个简单的Category类来创建自引用表。

public class Category
{
    public int CategoryId{get; set;}
    public string Name {get;set;
    public int? ParentId {get;set}
    public virtual Category Parent {get;set}

    public virtual ICollection<Category> Children {get;set;}
}

EF生成的创建视图具有新类别名称的开箱即用区域:

@Html.LabelFor(model => model.Name, new {@class = "control-label"})
@Html.EditorFor(model => model.Name,"", new{@class="form-control"}

和一个预先填充父类别选择的区域

@Html.LabelFor(model => model.ParentId, "Parent Category", new {@class = "control-label"})
@Html.DropdownList("ParentId", null, new {@class ="form-control})

这允许具有许多嵌套子类别的类别以及嵌套在其他子类别之下的其他子类别,等等...等等...

创建视图允许您使用@Html.DropdownList创建新类别并分配父类别,该@Html.DropdownList拉出所有类别的文本值,但仅列出实际类别或子类别名称。

有没有一种方法可以更改@Html.DropdownList的显示值以显示层次树,而不是单个父值?

因此, @Html.Dropdownlist显示父类别的完整层次结构值,而不是@Html.Dropdownlist显示“ AAA电池”(新类别的父类别的值):

Electronic Supplies >> Batteries >> AAA Batteries

当然,这是一个名为“电子用品”的类别,其子类别为“电池”,而子类别为“ AAA电池”。

您的模型中需要一个为您生成此名称的方法。 就像是:

public class Category
{
    public int CategoryId {get; set;}
    public int ParentId {get; set;}
    public string Name {get; set;}

    public string GetFullCategoryName()
    {
        string result = this.Name;

        // note: I removed the argument because it's class member.
        Category parent = this.GetParent(); // null for top level Categories

        while (parent != null)
        {
            result = parent.Name + " >> " + result;
            parent = GetParent(parent.ParentId);
        }

        return result;
    }

    public Category GetParent()
    {
        // note: I just made this up, you would use whatever EF method you have...
        return EF.GetEntity<Category>(this.ParentId);
    }
}

当然,您还需要一个GetParent方法...

编辑:

这是一个使用此示例(假设存在一个具有CategoryId属性和GetAllCategories方法的模型)的示例:

@Html.DropDownListFor(x => x.CategoryId, Model.GetAllCategories().Select(c => new SelectListItem() { Text = c.GetFullCategoryName(), Value = c.CategoryId }))

编辑2:我更改了上面的代码以显示整个类,也许这样做更有意义?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM