Bind data with nested object using Knockout MVC in MVC 4

本秂侑毒 提交于 2019-12-13 03:44:28

问题


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; }
}

And here is my 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)

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.

Editted! Here is part of the auto-generated HTML:

The binding:

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

The view model:

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

回答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>


来源:https://stackoverflow.com/questions/17918628/bind-data-with-nested-object-using-knockout-mvc-in-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!