2015-01-05 3 views
1

저는 MVC에 익숙하며 MVC에서 CreateEmployee 폼을 만들려고합니다. 당분간, 내가 달성하고자하는 모든 것은 Departments에 대해 양식의 드롭 다운 목록을 추가하는 것입니다. 드롭 다운 목록은 데이터베이스에서 채워지고 Visual Studio를 사용하여 DB에 연결되어 테이블의 모든 코드 파일을 만들었습니다. 이것은 작성 양식이 보여야하는 것입니다. 아래 양식은 각도 j를 사용하여 작성됩니다.MVC의 동적 드롭 다운 목록

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

비주얼 스튜디오

부서 표

using System; 
using System.Collections.Generic; 

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

그리고 당신은 컨트롤러의 DB를 조회해야

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

답변

2

부서 테이블 문맥을 생성하는 테이블 코드입니다 그것을보기에 공급하십시오. 모델을 통해 : 액션

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 
             })) 
+0

ChrFin 당신은 f **** g 최고입니다. 고마워요, 고맙습니다. – nahaelem

+0

안녕 ChrFin. 제출을 클릭하면 다른 모든 필드가 드롭 다운 목록을 제외한 값을 반환한다는 것을 알게되었습니다. 무엇이 원인인지 알 수 있습니까? 덕분에 – nahaelem

+0

@ user3761259 : 생성 된 HTML을 표시 할 수 있습니까? – ChrFin

관련 문제