首页 > 解决方案 > 如何在 ASP.NET Core MVC 中使用数据库中的数据制作下拉列表

问题描述

我已经想出了如何使用静态数据制作下拉列表,但我想显示数据库中的数据。如何使用来自模型 Neighbourhoods 的数据填写我的列表?我想在我的下拉列表中显示所有 NeighbourhoodNames。

我正在使用带有 MVC 的 .net core 5.0

我的cshtml代码:

    <select asp-for="Neighbourhood" asp-items="Model.NeighbourhoodList"></select>

我的模型:

    using Microsoft.AspNetCore.Mvc.Rendering;
    using System;
    using System.Collections.Generic;
    using Microsoft.EntityFrameworkCore;

    namespace MyProject.Models
    {
        [Keyless]
        public partial class Neighbourhoods
        {
            public string NeighbourhoodGroup { get; set; }
            public string NeighbourhoodName { get; set; }
            public List<SelectListItem> NeighbourhoodList { get; } = new List<SelectListItem>
            {
                new SelectListItem { Value = "a", Text = "New York" },
                new SelectListItem { Value = "b", Text = "Los Angeles" },
            };
        }
    }

我的控制器:

        // GET: Neighbourhoods/Create
        public IActionResult Create()
        {
            var vm = new Neighbourhoods();
            return View(vm);
        }

标签: c#asp.net-mvc

解决方案


推荐阅读