【问题标题】:Dropdown list with items from database in MVC带有 MVC 中数据库项目的下拉列表
【发布时间】:2021-09-17 10:16:36
【问题描述】:

我有这两个模型

  public class FileType
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }



public class Genre
    {
        public int Id { get; set; }

        public string Name { get; set; }

        [ForeignKey("FileType")]
        public int FileTypeID { get; set; }
    }

以及这些模型在 PostgreSQL 数据库中的数据表,我想在视图中创建 2 个下拉列表,名称为文件类型,名称为流派。我想在此上传视图中创建 2 个 ddl

 public class FileUploadViewModel
    {
        public List<FileModel> Files { get; set; }
        public string Name { get; set; }
        public string Extension { get; set; }
        public string Description { get; set; }
        public string Author { get; set; }
        public string Year { get; set; }
        public string FilePath { get; set; }
        public string PublishedOn { get; set; }
        public int DownloadCounter { get; set; }
     
    }

【问题讨论】:

标签: c# asp.net-mvc postgresql asp.net-core model-view-controller


【解决方案1】:

如果你想为FileTypeID 创建一个下拉列表,你可以试试这个:

(...)
public class Genre
    {
        public int Id { get; set; }

        public string Name { get; set; }

        [ForeignKey("FileType")]
        public FileType FileTypeID { get; set; }
    }

public enum FileType
{
Item1,
Item2,
Item3,
Item4
}

那么,在你看来:

@model YourNameSpace.Models.Genre

@{
    ViewData["Title"] ="xyz";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@Html.DropDownListFor(m => m.FileTypeID, new SelectList(Enum.GetValues(typeof(FileType))), "Select FileType", new { @class = "form-control" })

然后您将看到一个下拉列表,其中包含四个可选项目item1-item4 和一个默认占位符,说明“选择文件类型”。

【讨论】:

  • 我想从数据库而不是枚举中绑定数据
  • 嗯,你不能通过视图与数据库通信,除非你使用模型来做到这一点。模型是您通往数据库的门户。在某些时候,模型需要与数据库齐平。我认为唯一的问题是:先使用代码还是先使用数据库。我建议先创建模型,然后使用 EF 迁移来创建数据库。在迁移之前在启动文件的 ConfigureServices 中设置您的 db 参数,它应该全部刷新。到目前为止,这有意义吗?
  • 我了解你,我在 db 中有模型和表,我也用数据填充表。我知道如何从表中获取元素。但是假设我从 db 获取数据并将其存储在 uploadviewmodel 中将该模型传递给视图我知道如何执行此操作,但我不知道如何在视图的下拉列表中显示它。
猜你喜欢
  • 1970-01-01
  • 2016-07-06
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多