使用MVC 4中的Knockout MVC将数据与嵌套对象绑定

时间:2013-07-29 07:50:00

标签: asp.net-mvc-4 knockout.js knockout-mvc

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

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>也是如此。这有什么不对的?我想在绑定上下文时出了点问题。请帮我。非常感谢你。

Editted!以下是自动生成的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}};

1 个答案:

答案 0 :(得分:1)

感谢nemesv的评论,我找到了解决方案。要访问嵌套对象,这里是Product,我们使用With绑定。以下是视图的代码:

@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>