如何在 Html.DropDownListFor 上选择显示的文本

How to choose displayed text on Html.DropDownListFor

如何选择某种类型的 属性 显示在 Html.DropDownListFor 中?

例如,我有以下 class,我想从中 select 值

public partial class Artysta
    {
        public Artysci()
        {
            this.SpektaklArtysta = new HashSet<SpektaklArtysta>();
        }

    [Key]
    public int ArtystaID { get; set; }

    public string Imie { get; set; }

    public string Nazwisko { get; set; }        
}

这是为编辑视图生成的代码,有时会显示 Imie,有时会显示 Nazwisko

@using (Html.BeginForm())
{
@model Teatr.Models.SpektaklArtysta
<div class="form-group">
            @Html.LabelFor(model => model.ArtystaID, "Artysta", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ArtystaID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ArtystaID, "", new { @class = "text-danger" })
            </div>
        </div>
}

我想将显示 属性 设置为 Nazwisko,我该如何实现?

更新:

这是生成此视图的实际模型。

public partial class SpektaklArtysta
    {
        public int SpektaklID { get; set; }

        public int ArtystaID { get; set; }

        public int RolaArtystyID { get; set; }

        [Key]
        public int SpektaklArtystaID { get; set; }

        public virtual Artysci Artysci { get; set; }

        public virtual RolaArtysty RolaArtysty { get; set; }

        public virtual Spektakle Spektakle { get; set; }
    }

一个不错的选择是使用 DropDownList 如下

@Html.DropDownList("DropDownId", Model.Select(item => new SelectListItem
{
    Value = item.ArtystaID.ToString(),
    Text = item.Nazwisko.ToString(),
     Selected = "select" == item.ArtystaID.ToString() ? true : false
}))

希望能回答您的问题!

好的,您实际上需要将可能值列表传递给下拉列表,例如:

@Html.DropDownListFor(model => model.ArtystaID, new SelectList(Model.Artysci, "ArtystaID", "Nazwisko", 0))

它说:DropDownList 设置模型 ArtystaID 字段,由模型 Artysci 字段填充,该字段应该包含在 ArtystaID 字段下具有键并在 Nazwisko 字段下显示文本的项目(所以, 你的 Artysta class).

现在,您的 class 没有 Artysci 字段,因此您必须创建它:

public partial class Artysta
    {
        public Artysci()
        {
            this.SpektaklArtysta = new HashSet<SpektaklArtysta>();
        }

    [Key]
    public int ArtystaID { get; set; }

    public string Imie { get; set; }

    public string Nazwisko { get; set; }      

    public List<Artysta> Artysci = ArtistRepository.GetAllArtists();
}

或者直接在DropDownList中传递:

@Html.DropDownListFor(model => model.ArtystaID, new SelectList(ArtistRepository.GetAllArtists(), "ArtystaID", "Nazwisko", 0))

哦,只是个人注意事项:我知道这可能不是您的选择,除非您是 lead/sole 开发人员,但请为您的 classes、变量等使用英文名称,如果将来其他人必须处理您的代码,并且他们可能不会说波兰语,那将会容易得多;)