【问题标题】:How to databind a dropdownlist using knockout and MVC and Entity Framework如何使用淘汰赛和 MVC 和实体框架对下拉列表进行数据绑定
【发布时间】:2015-09-08 01:54:09
【问题描述】:

我有两个级联下拉列表,我想根据我的 knockout.js 进行绑定。本质上,我想要实现的是两个下拉列表,它们从数据库中为公司的每个分支填充,一个将根据在另一个下拉列表中选择的分支填充各个部门。我在转换为列表然后绑定到下拉列表时遇到问题。

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

查看

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

存储库

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

控制器

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

【问题讨论】:

  • 您定义了CompanyViewModel 构造函数,然后将其重新分配给自身的一个实例?它应该工作,但那是令人反感的。最好将其创建为普通对象。您的绑定不应使用模型的名称。分支绑定应该简单地绑定到Branch,部门绑定到DepartmentoptionsValueoptionsText 可能不应该是函数。我们需要查看 Branch 和 Department 数据的样子,才能确切了解需要如何设置,但很可能它们只是 Branch 的 BranchIdBranchName,Department 的数据类似。

标签: c# asp.net-mvc entity-framework knockout.js


【解决方案1】:

您可以通过以下方式实现级联下拉列表:

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

【讨论】:

    猜你喜欢
    • 2012-11-29
    • 2013-12-30
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    相关资源
    最近更新 更多