0

我正在使用Knockout MVCfrom here将淘汰赛集成到我的网站,但我遇到了问题。如果我的模型包含另一个对象,则绑定将不成功。例如,这是我的模型:

public class HelloWorldModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [Computed]
    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }

    public ProductModel ProductModel { get; set; }
}

这是我的ProductModel

public class ProductModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public bool IsActive { get; set; }
}

这些模型仅用于测试,因此非常简单。这是我要显示的视图:

@using PerpetuumSoft.Knockout
@model MyStore.UI.Models.HelloWorldModel

@{
    ViewBag.Title = "HelloWorld";
    var ko = Html.CreateKnockoutContext();
}

<p>
    Name: @ko.Html.TextBox(x => x.ProductModel.Name)
</p>
<p>
    Price: @ko.Html.TextBox(x => x.ProductModel.Price)
</p>
<h2>
    Product @ko.Html.Span(x => x.ProductModel.Name), @ko.Html.Span(x => x.ProductModel.Price)
</h2>

<p>First name: @ko.Html.TextBox(m => m.FirstName)</p>
<p>Last name: @ko.Html.TextBox(m => m.LastName)</p>
<h2>Hello, @ko.Html.Span(m => m.FullName)!</h2>

@ko.Apply(Model)

但它失败了。什么都没有出现。<input/>是空白的,<span>. 这里有什么问题?我想绑定上下文有问题。请帮我。太感谢了。

已编辑!这是自动生成的 HTML 的一部分:

绑定:

Name: <input data-bind="value : ProductModel().Name" />

视图模型:

var viewModelJs = {"FirstName":"AAA","LastName":"BBB","FullName":"AAA BBB","ProductModel":{"Id":0,"Name":"Coca Cola","Price":123.0,"CategoryId":0,"IsActive":false}};
4

1 回答 1

1

Thanks to nemesv's comment, I've found the solution. To access the nested object, here is Product, we use With binding. Here is the code for the view:

@using (var product = ko.With(x => x.ProductModel))
{
    <p>
        Name: @product.Html.TextBox(x => x.Name)
    </p>
    <p>
        Price: @product.Html.TextBox(x => x.Price)
    </p>
    <h2>
        Product @product.Html.Span(x => x.Name), @product.Html.Span(x => x.Price)
    </h2>
}

<p>First name: @ko.Html.TextBox(m => m.FirstName)</p>
<p>Last name: @ko.Html.TextBox(m => m.LastName)</p>
<h2>Hello, @ko.Html.Span(m => m.FullName)!</h2>
于 2013-07-29T09:21:13.123 回答