c# - 带有动态数据的 .NET MVC 下拉菜单

我正在学习使用 .NET MVC 在 Visual Studio 上创建应用程序。我正在尝试从我的一个模型中添加一个包含动态数据的下拉列表。这个想法是,当添加“项目”时,它会使用名称在下拉列表中选择一个“客户端”(先前创建的)。

我的“项目”类如下所示:

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
}

我能够使用枚举“类型”为项目类型创建下拉列表:

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

这是我的客户课程:

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

当我尝试添加下拉列表时,我无法选择要在 dropdwon 中使用的名称 value。像这样的东西,但我不确定_____空间发生了什么:

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

任何帮助表示赞赏。谢谢!

回答1

我设法创建了一个静态类并生成了下拉列表,但它没有显示任何数据,即使我认为我已经在数据库中有数据。这是我的新静态类,仅包含客户端名称和 ID,我将其转换为具有 ClientID 和名称作为属性的项目列表:

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

下拉菜单建立在视图上:

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

我确定我错过了一些东西,但我不确定是什么。我是否需要在 crontroller 部分添加一些东西才能使其工作?提前致谢!

相似文章

随机推荐

最新文章