MVC中的动态DropDown列表

时间:2015-01-05 15:35:41

标签: c# asp.net-mvc asp.net-mvc-4

我是MVC的新手,我正在尝试在MVC中创建一个CreateEmployee表单。目前,我想要实现的是将Departments的poulated下拉列表添加到表单中。 dropdownlist是从数据库填充的,使用Visual Studio,我连接到DB,它创建了表的所有代码文件。这就是创建表单应该是什么样子。下面的表单是使用Angular js创建的。

enter image description here

这是我的Createform模型。

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();
 }

以下是visual studio生成的表格代码

部门表

using System;
using System.Collections.Generic;

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

和部门表格背景

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

1 个答案:

答案 0 :(得分:3)

您应该在控制器中查询数据库并将其提供给View,例如通过模型:

将以下内容添加到您的模型中:

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

并在你的行动中:

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

然后在您的视图中,您可以执行以下操作:

@Html.DropDownListFor(m => m.Department,
     Model.Departments.Select(d => new SelectListItem()
                                       {
                                           Value = d.id.ToString(),
                                           Text = d.Department 
                                       }))