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);
        }
3
  • 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? Commented Jun 5, 2020 at 9: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? Commented Jun 5, 2020 at 9:55
  • You need to start learning about how to connect to database and get data from database in C#. Look here for one of the answers on SO. Example1 Example2 Commented Jun 5, 2020 at 11:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.