0

I have figured out how to make a dropdownlist with static data, but I want to display data from my database. How do I fill my list with data from the model Neighbourhoods? I want to display all the NeighbourhoodNames in my dropdown.

I am using .net core 5.0 with MVC

My cshtml code:

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

My Model:

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

My Controller:

        // GET: Neighbourhoods/Create
        public IActionResult Create()
        {
            var vm = new Neighbourhoods();
            return View(vm);
        }
Tim MG
  • 426
  • 5
  • 17
  • In Controller where you are creating model object, you should write code to get data from database and populate the List property of the model object. What's the issue you are facing in writing that code? – Chetan Jun 05 '20 at 09:38
  • @ChetanRanpariya The issue is that I have no idea how to do that. I'm a beginner when it comes to MVC programming. Could you show me an example? – Tim MG Jun 05 '20 at 09:55
  • You need to start learning about how to connect to database and get data from database in C#. Look [here](https://stackoverflow.com/questions/18613851/asp-net-mvc-dropdown-list-from-database) for one of the answers on SO. [Example1](https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/) [Example2](https://parallelcodes.com/bind-populate-asp-net-mvc-dropdownlist-from-database/) – Chetan Jun 05 '20 at 11:15

0 Answers0