Search code examples
asp.net-mvcdropdown

Dropdown list population from ViewModel


First of all, I know this question has been asked many, many times. I've read countless articles and Stack Overflow answers. I've tried to figure this problem out for four days and I think I need help if someone doesn't mind.

I have two databases. The employee database has a field called "DisplayName" -- the second database has a relationship with the first and they work together great. I'm able to call the two databases perfectly in another application.

You can see the in the picture Index Page that I have a list of people. I want a dropdown below it that lists all display names in the database so employees can add themselves to the list. You'll see a dropdown in the image but it's not populated.

Seems simple. But geez. Part of a problem I'm having is my home controller already has a function to populate the list in the picture so I can't do another on that page. I've tried a lot of suggestions on a lot of sites. I get IEnumerable errors or display reference errors....

Here's my controller (again - it has nothing in it that helps the dropdown):

namespace SeatingChart.Controllers
{
    public class HomeController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();


        // GET: Employee
        public ActionResult Index()
        {

            var lists = db.BreakModels
                            .Include("Employee")
                            .Include("TimeEntered")
                            .Include("TimeCleared")
                            .Include("DisplayName")
                            .Select(a => new HomeIndexViewModels
                            {
                                Employee = a.Employee,
                                DisplayName = a.EmployeeModels.DisplayName,
                                TimeEntered = a.TimeEntered,
                                TimeCleared = a.TimeCleared.Value,
                                Id = a.EmployeeModels.Id,
                            });

            return View(lists);
        }

View:

    @model IEnumerable<SeatingChart.Models.HomeIndexViewModels>

@{
    Layout = null;
}

@Html.Partial("_Header")

    <div class="container_lists">
        <div class="container_break col-md-8">
            <h5 style="text-align:center">Break List</h5>
            <table class="table-bordered col-lg-12">
                @if (Model != null)
                {
                    foreach (var item in Model)
                    {
                        if (item.TimeCleared == null)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DisplayName)
                                </td>
                                <td>
                                    &ensp;BV
                                </td>
                                <td>
                                    &ensp;@item.TimeEntered.ToString("HH:mm")
                                </td>
                            </tr>
                        }
                    }
                }
            </table>
            @using (Html.BeginForm())
            {
                <div class="row site-spaced">
                    <div class="col-3">
                        @Html.DropDownList("DisplayName", new SelectList(new List<string>() { "---Dispatcher---" }), new { @class = "required " })
                    </div>
                </div>
                <div class="col-3">
                    <input type="submit" value="Submit" class="site-control" />
                </div>
            }
        </div>
    </div>

ViewModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace SeatingChart.Models
{
        public class HomeIndexViewModels 
        {

        //Break Model
        public int BreakId { get; set; }
            public int Employee { get; set; }
            public DateTime TimeEntered { get; set; }
            public DateTime? TimeCleared { get; set; }

            //Employee Model
            public int Id { get; set; }
            public string DisplayName { get; set; }
            public string DisplayNames { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public bool NotActive { get; set; }
            public int Force { get; set; }

            public string EmployeeList { get; set; }


    }

}

I hope this is clear enough. I've tried so many different ways with so much code - the errors are different with everything I've tried.

Thanks in advance for your patience and help!


Solution

  • You can add to your viewmodel

    public List<SelectListItem> Employees { get; set; }
    

    Then you can populate this list with controller then in view just call it with:

    @Html.DropDownListFor(m => m.Id, Model.Employees, new { @class = "form-control", required = "required" })
    

    Update - how to populate list. Should work (but not tested code).

        public List<SelectListItem> GetEmployeeForDropdown(List<HomeIndexViewModels> list)
        {
            List<SelectListItem> empList = new List<SelectListItem>();
    
            try
            {
    
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            empList.Add(new SelectListItem { Text = item.DisplayName, Value = item.Id.ToString() });
                        }
                    }
                    else
                    {
                        empList.Add(new SelectListItem { Text = "No items", Value = string.Empty });
                    }
    
    
            }
            catch (Exception ex)
            {
                //handle exceptions here
            }
    
            return empList;
        }
    

    Edit: Remember to use your model in view!