Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c# - Dropdown list with items from database in MVC

I have this 2 models

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

And tables with data in PostgreSQL database for these models, i want to create 2 dropdownlists in view with Name for filetype and name for genre.I want to create that 2 ddl in this upload view

 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; }
     
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to create a dropdown list for FileTypeID, you could try this:

(...)
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
}

Then, in your view:

@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" })

You will then see a dropdown list with the four selectable items item1-item4 and a default placeholder stating "Select FileType".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...