尝试从sql查询绑定数据以查看下拉列表

时间:2016-02-08 00:18:23

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

我的示例代码如下:

持有列表项目的模型:

public IList<ListItem> ListOfRecords { get; set; }

在控制器中填充模型:

public ActionResult Index()
{
    var model = new ViewModel();
    model.ListOfEmployees = GetAllRecordsFromDataBase();
    return View(model);
}

我的观点:

<select data-bind="options: optionValues, selectedOptions: SelectedOptionValues"></select>

填充下拉列表的淘汰代码:

function DoNotCallModel(optionValues, SelectedOptionValues) {
var self = this;
self.optionValues = ko.observableArray(optionValues); 
self.SelectedOptionValues = ko.observable(SelectedOptionValues);
return self; 
}



@foreach (var item in Model)
            {
                <text>
                model.ContactUsers.push(new ContactModel('@item.Id',
            '@HttpUtility.JavaScriptStringEncode(item.InsertRequestedByEmployee)',
            '@HttpUtility.JavaScriptStringEncode(item.PhoneNumber)',
            '@HttpUtility.JavaScriptStringEncode(item.EmailAddress)',
            '@HttpUtility.JavaScriptStringEncode(item.Notes)',
            '@HttpUtility.JavaScriptStringEncode(item.InsertedBy)',
            '@item.InsertDate'
              ))
            </text>
            }
            window.model = model;
            ko.applyBindings(model);

我不确定如何将模型中的数据填充到此下拉列表中。我已经使用knockout对输入类型进行了数据绑定。第一次尝试下拉。

1 个答案:

答案 0 :(得分:0)

假设您正在尝试将复杂对象绑定到下拉列表,则需要多个绑定。

optionsText - 定义要显示的文本

optionsValue - 所选选项的值应为

value - 选择一个选项后的下拉列表值(在viewmodel中单独可观察)

//Contract type collection
self.ContractTypes = ko.observableArray();

//ContractType object
self.ContractType = function (data) {
    this.ContractType = ko.observable(data.ContractType);
    this.ContractTypeId = ko.observable(data.ContractTypeID);
};

//Value of selected contract type
self.SelectedContractType = ko.observable();

<select data-bind="options: ContractTypes, optionsText: 'ContractType', optionsValue: 'ContractTypeId', value: SelectedContractType></select>

您的装订内容适用于同时选择的多个选项。