我在服务器端创建模型并使用它像ViewModel进行淘汰。 我的问题是绑定到选择值对象{代码,名称}或任何想法如何更改代码值也改变名称,我需要选择文本和值将依赖于可观察
我的模型c#
public class Model
{
public ClientInfo ClientInfo = new ClientInfo();
public Address Address = new Address();
public SearchInfo SearchInfo = new SearchInfo();
}
public class ClientInfo
{
public string firstname = "Sunnatilla";
public string lastname = "Axakalov";
}
public class Address
{
public List<CodeName> countries = new List<CodeName>();
public CodeName country = new CodeName();
public List<CodeName> cities = new List<CodeName>();
public CodeName city = new CodeName();
}
public class CodeName
{
public string code = "2";
public string name = "Russia";
public CodeName(){}
public CodeName(string code, string name)
{
this.code = code;
this.name = name;
}
}
public class SearchInfo
{
public bool NewClient = true;
}
Aspx Page
<select id="address" data-bind="options: Address.countries,
optionsText: 'name',
optionsValue: 'code',
value: Address.country.code,
event: { change: Address.country.name = ko.utils.arrayFirst(Address.countries, function (country) { if (country.code === Address.country.code) return country.name }) }"></select>
<span data-bind="text: Address.country.code"></span>
<span data-bind="text: Address.country.name"></span>
<script>
$("#out").html('<%=this.model %>');
var jsonModel = JSON.parse('<%=this.model %>');
// jsonModel = {"ClientInfo":{"firstname":"Sunnatilla","lastname":"Axakalov"},"Address":{"countries":[{"code":"1","name":"Kazakhstan"},{"code":"2","name":"Russia"},{"code":"3","name":"China"}],"country":{"code":"2","name":"Russia"},"cities":[],"city":{"code":"2","name":"Russia"}},"SearchInfo":{"NewClient":true}}
function ViewModel() {
ko.mapping.fromJS(jsonModel, {}, this); // here I creatre my view model, all childs recursively observable
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
</script>
或者在更改时发生一些事件Address.country.code也改变了Address.country.name
if select option value changed Address.country.code = 1 => Address.country.name = "Kazakhstan"
if select option value changed Address.country.code = 2 => Address.country.name = "Russia"
if select option value changed Address.country.code = 3 => Address.country.name = "China"
我需要同时更改配对键/值
请帮忙。
答案 0 :(得分:0)
也许它不起作用,因为当价值发生变化时,你会覆盖一个观察站Address.country.name
<select id="address" data-bind="options: Address.countries,
optionsText: 'name',
optionsValue: 'code',
value: Address.country.code,
event: { change: Address.country.name(ko.utils.arrayFirst(Address.countries, function (country) { if (country.code === Address.country.code) return country.name }) })"></select>