尝试将 sql 查询中的数据绑定到下拉列表的视图
本文关键字:数据绑定 下拉列表 视图 sql 查询 | 更新日期: 2023-09-27 18:33:40
我的示例代码是这样的:
保留列表项的模型:
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);
不确定如何将模型中的数据填充到此下拉列表中。我已经使用输入类型的挖空完成了数据绑定。第一次尝试下拉列表。
假设您尝试将复杂对象绑定到下拉列表,则还需要多个绑定。
选项文本 - 定义要显示的文本
选项值 - 所选选项的值应是多少
值 - 选择选项后下拉列表的值(在视图中单独观察模型)
//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>
您的绑定内容是同时选择多个选项。