无法使用Knockoutjs将MVC模型绑定到Razor中

时间:2015-10-17 22:50:55

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

我知道这应该很简单,可能会有很多文章和例子。但是,我仍然无法使其发挥作用。如果可以的话,请先在发送解决方案之前先尝试一下。此外,如果您使用任何lib或扩展名,请在回复中提及。非常感谢你!

我的问题 - 无法绑定MVC模型(IEnumerable),通过控制器索引返回到PartialView。

控制器

public ActionResult Index()
{
    Books = db.BookDB.ToList();
    Authors = db.AuthorDB.ToList();
    objBookAuthorViewModel.Authors = Authors;
    objBookAuthorViewModel.Books = Books;
    return View("~/Views/Book/Index.cshtml", objBookAuthorViewModel);
}

索引视图(调用部分视图)

@model KnockOutJsMvcCreateArticle.Models.BookAuthorViewModel
@using KnockOutJsMvcCreateArticle.Models
@using Newtonsoft.Json;
....
<div id="_indexPartialAuthor">
    <div class="col-md-10">
        <div class="panel panel-danger">
            <div class="panel-heading">
                <h2 class="panel-title"># of Authors @Model.Authors.Count</h2>
            </div>
            <div class="panel-body">
                @Html.Partial("~/Views/Shared/_Author.cshtml", Model.Authors)
            </div>
        </div>
    </div>
</div>

部分视图

@using KnockOutJsMvcCreateArticle.Models
@using Newtonsoft.Json;
@model IEnumerable<KnockOutJsMvcCreateArticle.Models.Author>
....
<script src="~/Scripts/Knockout.mapping-2.4.1.js"></script>

<table class="table table-bordered table-striped table-condensed">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(model => model.FirstName)</th>
            <th>@Html.DisplayNameFor(model => model.LastName)</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: Authors">
        <tr>
            <td data-bind="text:FirstName"></td> <!--Not really using Models-->
            <td data-bind="text:LastName"></td>
        </tr>
    </tbody>
</table>

<script type="text/javascript">
    var viewModel = @Html.Raw(Json.Encode(Model));
    ko.applyBindings(viewModel);
</script>

1 个答案:

答案 0 :(得分:0)

您忘记将MVC模型映射到淘汰模型,因为淘汰需要为所有MVC模型属性创建可观察属性:

ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));

我认为用这个替换脚本应该可以解决问题(正如你可能看到我在这里使用JQuery):

<script type="text/javascript">
    $(document).ready(function () {  
         var viewModel = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
         ko.applyBindings(viewModel);
    });   
</script>

更新向viemodel添加方法:

<script type="text/javascript">

function viewModel() {
    this.details = function () {
        alert("de");
    };
};

$(document).ready(function () {
    var json = '@Html.Raw(JsonConvert.Encode(Model))';

    //Map MVC model:
    var mvcModel = ko.mapping.fromJSON(json);

    //create view model that contains extension methods:
    var myViewModel = new viewModel();

    //update this model with properties from MVC model:
    var koModel = ko.mapping.fromJS(myViewModel, mvcModel);

    ko.applyBindings(koModel );
});        
</script>