'.NET MVC dropdown with dinamic data

I'm learning to use .NET MVC creating an app on Visual Studio. I'm trying to add a dropdown with dinamic data from one of my Models. The idea is that when a "project" is added, it selects one "client"(created previously) on the dropdown using the name.

My "Project" class looks as follows:

public class Project
{
    [Key]
    public int ProjectID { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Client { get; set; }
}
public enum Type
{
    NewProject,
    OldProject,
    InteriorDesign,
    ExteriorDesign
}

I was able to create a dropdwon for the type of project using the enum "Type":

         @Html.DropDownListFor(
                model => model.Type,
                new SelectList(Enum.GetValues(typeof(Type))),
                "Type of project",
                new { @class = "form-control" }
                )

This is my Client class:

    public class Client
        {
            [Key]
            public int ClientID { get; set; }
            public string Name{ get; set; }
            public virtual ICollection<Project> Project{ get; set; }
        }

An when I try to add the dropdown, I don't manage to select the Name value to be used in the dropdwon. Something like this but I'm not sure what goes on the _____ spaces:

           @Html.DropDownListFor(
                model => model.Client,
                new SelectList(__________________),
                "Client name",
                new { @class = "form-control" }
                )

Any help is appreciated. Thanks!



Solution 1:[1]

I managed to create a static class and generate the dropdown, but it doesn't show any data, even thought I already have data on the database. This is my new static class that contains only the clients Names and IDs, I transform it into a List of items with ClientID and Name as atributes:

    public static class ClientList
    {
        public static Client client = new Client();
        public static IEnumerable<Client> Clients = new List<Client>
        {
            new Client {ClientID= client.ClientID,
                        Name = client.Name
            }
        };
    }
}

And the dropdown build on the view:

 @Html.DropDownListFor(
                    model => model.Client,
                    new SelectList(ClientList.Clients, "ClientID", "Name"),
                    "Client name",
                    new { @class = "form-control" }
                    )

I'm sure I'm missing something, but I'm not sure what. Do I need to add something on the crontroller part for this to work? Thanks in advance!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nestor