繁体   English   中英

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

[英]How to choose displayed text on Html.DropDownListFor

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

例如,我有以下类,我想从中选择值

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; }        
}

这是一个生成的编辑视图代码,有时会显示ImieNazwisko

@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; }
    }

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

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

它说:DropDownList的设置模式ArtystaID场,这是由模型Artysci场,这是应该包含有以下主要项目填充ArtystaID领域和显示文本下Nazwisko场(所以,你的Artysta类)。

现在,您的班级没有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))

哦,只是个人注意事项:我知道这可能不是你的选择,除非你是一个主要/唯一的开发人员,但请为你的课程,变量等使用英文名称,如果将来其他人将会更容易必须处理你的代码,他们可能不会说波兰语;)

对您而言,一个不错的选择是使用DropDownList ,如下所示

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

希望能回答您的要求!

暂无
暂无

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

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