Skip to content Skip to sidebar Skip to footer

How To Choose Displayed Text On Html.dropdownlistfor

How can I choose which property is displayed in Html.DropDownListFor for a some type? For example I have the following class from which I want to select values public partial class

Solution 1:

Ok, you need to actually pass a list of possible values to the dropdown list, for example like this:

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

It says: DropDownList setting models ArtystaID field, which is populated by models Artysci field, which is supposed to contain items that have key under ArtystaID field and display text under Nazwisko field (so, your Artysta class).

Now, your class doesn't have Artysci field, so you have to create it:

publicpartialclassArtysta
    {
        publicArtysci()
        {
            this.SpektaklArtysta = new HashSet<SpektaklArtysta>();
        }

    [Key]
    publicint ArtystaID { get; set; }

    publicstring Imie { get; set; }

    publicstring Nazwisko { get; set; }      

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

Or you can pass it directly in DropDownList:

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

Oh, and just a personal note: I know it's probably not your choice, unless you are a lead/sole developer, but please use English names for your classes, variables etc., it will be much easier if in the future someone else will have to work on your code, and they might not speak Polish ;)

Solution 2:

One good option for you is to use the DropDownList as following

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

Hope that answers your request!

Post a Comment for "How To Choose Displayed Text On Html.dropdownlistfor"