Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic DropDown list in MVC

I am very new to MVC and I am trying to make a CreateEmployee form in MVC. for now, all I am trying to achieve is to add the poulated dropdownlist for Departments to the form. the dropdownlist is populated from a database, and using Visual Studio, I connected to the DB and it created all the code file for the table. This is what the create form should look like. The form below is created using Angular js.

enter image description here

here is my Createform model.

public class CreateEmployee
{
    public int Id { get; set; }
    public string FullName { get; set; }
    [Required]
    public string Notes { get; set; }

   //add the dropdown list of departments here,i not sure on what to do here
   //do i create an instance of dbcontext here or AngtestDepartment


    public bool PerkCar { get; set; }
    public bool PerkStock { get; set; }
    public bool PerkSixWeeks { get; set; }
    public string PayrollType { get; set; }
}

 public ActionResult CreateEmployee() 
 {


   return View();
 }

Here are the table codes that visual studio generated

Department Table

using System;
using System.Collections.Generic;

public partial class AngTestDepartment
{
    public int id { get; set; }
    public string Department { get; set; }
}

and the Department Table context

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

public partial class DepartmentDbContext : DbContext
{
    public DepartmentDbContext()
        : base("name=DepartmentDbContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<AngTestDepartment> AngTestDepartments { get; set; }

    public System.Data.Entity.DbSet<AngularForms2.Models.CreateEmployee> CreateEmployees { get; set; }
}
like image 860
nahaelem Avatar asked Aug 01 '26 05:08

nahaelem


1 Answers

You should query the DB in the controller and supply that to the View, e.g. via the model:

Add the following to your model:

public int Department { get; set; }
public IEnumerable<AngTestDepartment> Departments { get; set; }

and in your Action:

public ActionResult CreateEmployee() 
{
    using (var db = new DepartmentDbContext())
    {
        var model = new CreateEmployee();
        model.Departments = db.AngTestDepartments.ToList();
        return View(model);
    }
}

then inside your view you can do something like:

@Html.DropDownListFor(m => m.Department,
     Model.Departments.Select(d => new SelectListItem()
                                       {
                                           Value = d.id.ToString(),
                                           Text = d.Department 
                                       }))
like image 185
Christoph Fink Avatar answered Aug 03 '26 17:08

Christoph Fink