我有一个 ASP.NET MVC 站点,我正在尝试让 knockout-mvc 使用它。
我在名为的 C# 代码中创建了一个视图模型,Refund其中包含一个Voucher被调用的Voucher类型和一个List<Country>被调用的Countries. Voucher 有一个int名为的变量VoucherNumber
这个视图模型被传递到一个强定义的视图中Refund\Index
我试图让敲除-mvc 将 Refund.Voucher.VoucherNumber 中的值绑定到文本框,并将值绑定到Refund.Countries下拉列表中。在控制器上,我对 Voucher.Vouchernumber 的值进行了硬编码,并将两个国家添加到 Country 列表中。
这是我的查看代码:
@using Resources
@using PerpetuumSoft.Knockout
@model MVC.Models.RefundViewModel
@{
    var ko = Html.CreateKnockoutContext();
}
<div id="refundformcontainer">
    <div id="headersection">
        <div id="pagetitlecontainer">@Language.RefundVouchers</div>
        <div id="helpercontainer">
            <label id="lblhelper">To begin enter a voucher number or scan a barcode</label>
        </div>
    </div>
    <div id="vouchercontainer">
        <div id="voucherdetailscontainer">
            <h5>@Language.VoucherDetails</h5>
            <div id="vouchernumbercontainer" class="initialvoucherfield">
                @Html.LabelFor(x=>x.Voucher.VoucherNumber)
                @ko.Html.TextBox(x=>x.Voucher.VoucherNumber)
            </div>
            <div id="countrycontainer" class="initialvoucherfield">
                @Html.LabelFor(x=>x.Voucher.Country)
                <select ko.Bind.Options(x=>x.Countries).OptionsText("Name").OptionsValue("CountryId").Value(x=>x.Voucher.CountryId) ></select>
            </div>
        </div>
    </div>
</div>
@ko.Apply(Model);
当页面加载时,两个控件都没有绑定。
当我查看生成的源代码时,会生成以下代码
<script type="text/javascript">
    var viewModelJs = {"Refund":null,"Voucher":{"VoucherId":0,"VoucherNumber":123456789,"Country":null,"CountryId":0,"Retailer":null,"RetailerId":0,"PurchaseDate":"0001-01-01T00:00:00","CustomsStampDate":null,"InvoiceNumber":"","LineItems":[],"TotalPurchasePrice":0.0},"Countries":[{"CountryId":380,"Name":"Italy"},{"CountryId":724,"Name":"Spain"}]};
    var viewModel = ko.mapping.fromJS(viewModelJs);
    ko.applyBindings(viewModel);
</script> 
knockout-2.2.0.js 和 knockout.mapping-latest.js 都包含在页面中
我得到的错误是
0x800a139e - JavaScript runtine error: Unable to parse bindings
Message: [Object Error]
Bindings value: Voucher().VoucherNumber
然后我更改了 Refund View 模型,使其具有属性 VoucherNumber 并让文本框引用它而不是 Voucher.VoucherNumber 属性
@ko.Html.TextBox(x=>x.VoucherNumber)
当我运行它时,我遇到了同样的无法解析绑定错误,但这次是针对国家/地区
Bindings value: options : Countries, optonsText : Name, optionsValue : CountryId
有人知道是什么原因造成的吗?