查看和ViewModel连接

时间:2014-05-22 19:38:59

标签: javascript html asp.net-mvc mvvm knockout.js

我有两个文件(一个View和一个ViewModel),但是我无法弄清楚如何让视图读取存储在模型中的信息并显示它。我在这个网站上看了几个相关的问题,但还没有找到我能够上班的任何东西。这可能只是因为我不完全理解已经给出的解决方案,但我希望发布这个可以让人们详细说明与我正在进行的项目直接相关的解决方案。

查看文件:

@{
    ViewBag.Title = "Sponsors";
}

<hgroup class="title">
    <h1>@ViewBag.Title</h1>
</hgroup>

<table>
    <thead><tr>
        <th></th><th>Sponsor</th><th>Description</th>
    </tr></thead>
    <!-- Todo: Generate table body -->
    <tbody data-bind="foreach: sponsor">
        <tr>
            <td></td>
            <td><select data-bind="text: cName"></select></td>
            <td><select data-bind="text: sDescribe"></select></td>
        </tr>
    </tbody>
</table>

ViewModel文件:

    ko.applyBindings({
sponsor: [
        self.companyNames = [
            { cName: "company1", sDescribe: "company 1 been nice enough to support my bowling career by paying for a couple of my tournaments." },
            { cName: "company2", sDescribe: "I am an employee at company 2 and it is where I purchase all of my equipment. The owner has also been nice enough to supply me with a few shirts to wear in tournaments and I have even received a few bowling balls from him." }
        ]);

我刚刚开始使用MVC框架,所以我还在学习。我一直在使用在线教程来到达我现在的位置。这个视图是我参与过的第三个视图,也是迄今为止唯一一个我无法展示的视图。其他人不使用javascript页面来显示他们的信息,因为他们的信息都没有动态加载。

1 个答案:

答案 0 :(得分:1)

您的视图模型应该是有效的JS对象。 喜欢以下

var viewModel = {
    sponsor: [
        { cName: "company1", sDescribe: "company 1 been nice enough to support my bowling career by paying for a couple of my tournaments." },
        { cName: "company2", sDescribe: "I am an employee at company 2 and it is where I purchase all of my equipment. The owner has also been nice enough to supply me with a few shirts to wear in tournaments and I have even received a few bowling balls from him." }
    ]
};

ko.applyBindings(viewModel);

请参阅小提琴http://jsfiddle.net/tabalinas/GHjRL/