简体   繁体   中英

How to databind a dropdownlist using knockout and MVC and Entity Framework

I have two cascading dropdownlists which I would like to bind based on my knockout.js. Essentially what I want to achieve is two dropdownlist that populate from a database for each branch of the company and one which will populate the various departments based on the branch that was selected in the other dropdownlist. I am having problems converting to a list and then binding to dropdownlist.

function CompanyViewModel() {

    var self = this;

    self.DepartmentName = ko.observable(" ")
    self.Department =ko.observableArray([]);
    self.DepartmentName = ko.Observable([]);
    self.Branch =ko.observableArray([]);
    self.BranchName = ko.Observable([])
}
CompanyViewModel = new CompanyViewModel();
ko.applyBindings(CompanyViewModel);


function  populateCompanyBranches() {

    $.ajax({
        type: "GET",
        $.when(getSecureData("/api/Branches/" ))
        .done(function (Branches) {
            Branch.unshift({ "BranchID": 0, "department name": "Please select a Branch." });
            CompanyViewModel.Branch(Branch);
        })
        .fail(function (message) {
            $.msgbox(message);
        });
};



function populateBranchDepartments() {
    $("#Branches").change(function () {
                var BranchID = $("#Branches").val();                           
                $.ajax({
                    type: "GET",
          $.when(getSecureData("/api/Departments/GetDepartment" + BranchID))
        .done(function (Department) {
        CompanyDepartment.unshift({ "CompanyID": 0, "departmentName": "Please select a department" });
            CompanyViewModel.Department(Department);
        })
        .fail(function (message) {
            $.msgbox(message);
            });
        };
}

View

Branch Name: <select data-bind="options:  CompanyViewModel. CompanyViewModel, optionsCaption: 'Select a Branch',
    optionsValue: function (item) { return item.BranchId; },
    optionsText: function (item) { return item.BranchName; }, value: Branch,
    valueUpdate: 'change'" id="Branches" name="Branch"></select>
<br />

Deaprtment Name: <select data-bind="options: CompanyViewModel.Department, optionsCaption: 'Choose Department...',
    optionsValue: function (item) { return item.DepartmentId; },
    optionsText: function (item) { return item.DepartmentName; },  value: DepartmentName,
    valueUpdate: 'change'" id="Department" name="Department"></select>
<br />   
  </div>

public class CompanyDTO
{
    public int BranchId { get; set; }
    public string BranchName { get; set;}  
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set;}  
}

public static class CompanyBranchList
{
    public static CompanyDTO DepartmentToBranchDTO(listing e)
    {
        return new CompanyDTO 
        {
            BranchId = e.BranchId,
            BranchName = e.BranchName
            DepartmentId = e.DepartmentId
            DepartmentName = e.DepartmentName

        };
    }


    public static List<CompanyDTO> ListBranchToDepartmentDTO(List<listing> e)       
    {
        List<CompanyDTO> lstCompanyDTO= e.Select(
          lstng => new CompanyDTO()
          {
            BranchId = lsting.BranchId,
            BranchName = lsting.BranchName
            DepartmentId = lsting.DepartmentId
            DepartmentName = lsting.DepartmentName
          }).ToList();
        return ListBranchToDepartmentDTO;
    }

Repository

public class CompanyRepository : IComapnyRepository
{
    public List<CompanyDTO> GetBranches()
    {
        using (TestDBEntities dbcontext1 = new TestDBEntities())
        {
            var lstCountries = from r in dbcontext1.Branches select r;
            List<CompanyDTO> lst = new List<CompanyDTO>();
            lst = CompanyBranchList.DepartmentToBranchDTO(lstCompanyDTO.ToList());
            return lst;
        }
    }

Controller

public List<CompanyDTO> GetDepartments(int deparmentId)
{
    using (TestDBEntities dbcontext = new TestDBEntities())
    {
        var lstDep = dbcontext.States.Where(b => b.DepartmentID == departmentId).ToList();
        List<CompanyDTO> list = new List<CompanyDTO>();
        list = CompanyBranchList.ListBranchToDepartmentDTO(lstDep.ToList());
        return list;
    }
}

You achieve cascading dropdown lists by doing this:

// the view model bound to the view
var vm = {
   branches: ko.observableArray([]),
   selectedBranch: ko.observable(),
   departments: ko.observableArray([]),
   selectedDepartment: ko.observable()
}

// subscription to listen to changes to the selected branch
vm.selectedBranch.subscribe(function(current, last){
   if(!current) return; // do nothing if nothing is selected
   if(current == last) return; // do nothing if nothing changed

   $.ajax({
      type: 'GET',
      url: '/api/Departments/GetDepartment/' + current.BranchId,
      contentType: 'application/json'
   })
  .then(function(result){
      vm.departments(result)
   });
}

// load the list of branches
$.ajax({
   type: 'GET',
   url: '/api/Branches',
   contentType: 'application/json'
})
.then(function(result){
   vm.branches(result); // populate branch observable array
   ko.applyBindings(vm);// bind view model to view
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM