DropDownListFor()指定具有自引用表的父级

时间:2021-10-20 00:14:31

In my PageModels I have:

在我的PageModels中我有:

public class Page : BaseModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PageID { get; set; }
    public int? ParentID { get; set; }
    public string Name { get; set; }

    public virtual Page Parent { get; set; }
    public virtual ICollection<Page> Children { get; set; }

    public Page()
    {
        this.Order = 0;
        this.Live = false; 
    }
}

public class CommodityPageMap : EntityTypeConfiguration<Page>
{
    public CommodityPageMap()
    {
        HasOptional(x => x.Parent)
            .WithMany(x => x.Children)
            .HasForeignKey(x => x.ParentID)
            .WillCascadeOnDelete(false);
    }
}

What I want to be able to do is have a drop down in my view that when selected sets the ParentID of my model. I'm not sure how to use DropDownListFor that would tie directly to my model.

我希望能够做的是在我的视图中有一个下拉列表,当选择时设置我的模型的ParentID。我不确定如何使用DropDownListFor直接绑定到我的模型。

Could someone point me in the right direction please?

有人能指出我正确的方向吗?

1 个解决方案

#1


1  

Setting the ParentID is just an integer, so as along as the values in the drop down list are integers that will work just fine.

设置ParentID只是一个整数,因此下拉列表中的值是可以正常工作的整数。

I guess the question you're really asking then is how to get the list of possible integers for this drop down list?

我想你问的那个问题是如何得到这个下拉列表中可能的整数列表?

Your model should have a property which returns that list. Something as simple as this:

您的模型应具有返回该列表的属性。像这样简单:

public IDictionary<int, string> PossibleParents
{
    get
    {
        // query the database for possible parents
        // return the list of IDs and names
    }
}

Then in your view you'd use that property to populate the drop down list:

然后在您的视图中,您将使用该属性填充下拉列表:

@Html.DropDownListFor(x => x.ParentID, new SelectList(Model.PossibleParents, "Key", "Value"))

#1


1  

Setting the ParentID is just an integer, so as along as the values in the drop down list are integers that will work just fine.

设置ParentID只是一个整数,因此下拉列表中的值是可以正常工作的整数。

I guess the question you're really asking then is how to get the list of possible integers for this drop down list?

我想你问的那个问题是如何得到这个下拉列表中可能的整数列表?

Your model should have a property which returns that list. Something as simple as this:

您的模型应具有返回该列表的属性。像这样简单:

public IDictionary<int, string> PossibleParents
{
    get
    {
        // query the database for possible parents
        // return the list of IDs and names
    }
}

Then in your view you'd use that property to populate the drop down list:

然后在您的视图中,您将使用该属性填充下拉列表:

@Html.DropDownListFor(x => x.ParentID, new SelectList(Model.PossibleParents, "Key", "Value"))