tags:

views:

43

answers:

1

hi, i'm buildin' an employee registration form in aspnet mvc, i have fields like "School" list in 1 dropdown box and "Department" list another, problem is i want to show Department list on change of School list, i have done followin' code:


public ActionResult EmployeeCreate()
{
   var getSchool = SchoolRepository.GetAllSchoolsInArray();//this gets school_id as value and school_name as text for dropdown box
   ViewData["SchoolsList"] = getSchool;

   return View();
} 


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EmployeeCreate()
{
   _employeeRepository.CreateEmployee(employeeToCreate);
   _employeeRepository.SaveToDb();
} 

Here is the View


Html.DropDownList("SchoolLists")
Html.DropDownList("DepartmentLists") 

now, how do i get the departments of selected school in dropdown boxes

+1  A: 

If you want to populate the Departments list based on the value of the selected School when this value changes you could use javascript and AJAX. So you setup a controller action which would return the departments for a given school:

public DepartmentsController: Controller
{
    public ActionResult Index(int? schoolId)
    {
        var departments = _depsRepo.GetDepartmentsForSchool(schoolId);
        return Json(departments);
    }
}

Once you have this controller you could use jQuery to register a change event of the schools drop down:

$(function() {
    $('#SchoolList').change(function() {
        var schoolId = $(this).val();
        $.getJSON('/departments/index', { schoolId: schoolId }, 
            function(departments) {
                var depsList = $('#DepartmentLists');
                depsList.empty();
                $(departments).each(function(i, department) {
                    // Id and Name used here should be properties
                    // of the department model
                    depsList.append(
                        '<option value="' + department.Id + '">' + 
                         department.Name + '</option>'
                    );
                });
        });
    });
});
Darin Dimitrov