在MVC 4中使用Knockout MVC将数据与嵌套对象绑定
我正在使用此处中的Knockout MVC
将击倒功能集成到我的网站,但是我遇到了问题.如果我的模型包含另一个对象,则绑定将失败.例如,这是我的模型:
I'm using Knockout MVC
from here to integrate knockout to my website, but I have a problem. If my model contains another object, the binding will be unsuccessful. For example, here is my model:
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; }
}
这些模型仅用于测试,因此非常简单.这是我要显示的视图:
These models are just for testing, so they're very simple. Here is my view to display:
@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>
也是如此.这是怎么了我猜绑定上下文有问题.请帮我.非常感谢.
But it's failed. Nothing appeared. <input/>
is blank, so does the <span>
. What's the wrong thing here? I guess something's wrong at binding context. Please help me. Thank you so much.
已编辑!这是自动生成的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}};
感谢nemesv
的评论,我找到了解决方案.要访问嵌套对象,这里是Product
,我们使用With
绑定.这是该视图的代码:
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>