ASP.NET MVC passes model to external KnockoutJS file

I read a lot of resources both in stackoverflow and in Google search engines, but it seems that nothing is concerned, in particular, my problem.

tl; dr I want to transfer my C # model from my view to an external JS file (Knockout) so that I can use this data from the model to display in my view.

Additional Information:

I have a pretty standard ASP.NET MVC 5 project with (for example), 1 view, 1 controller and a C # view model that is retrieved and the data is processed in my C # controller. My external JavaScript file contains knockout code, in particular, I want to put this C # module in the observable array in this external JS file so that I can leave my code for knockout from my view (except, possibly, a few lines).

Example:

books.js

var app = (function (app) {
    app.FilterBooks = function () {
        var self = this,
        books = ko.observableArray(myC#Model);

        var data = [];
        self.BooksList = ko.computed(function(){
            ko.utils.arrayForEach(books(), function (item) {
                data.push(item);
            });
        });
        return data;
    };
return app;
}(app || {}));

myC#Model is the C # model that I want to get from the view (or controller).

Index.html

@model viewModel

<div data-bind="foreach: BooksList">
    some knockout code in the view
    <p data-bind="text: bookName"></p>
</div>

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            var e = new app.FilterBooks;
            ko.applyBindings(e);
        });
    </script>
}

HomeController.cs

public ActionResult Index()
{
    //gets the list of all the books
    var viewModel = this.bookManager.GetAllBooks();
    return View(viewModel);
}

Idea:

One solution that I was thinking about would be to create a global variable, and then I could access it in any JS files referenced after that, but this solution seems less than ideal. An example of this might be:window.booksVM = @Html.Raw(Json.Encode(Model));

, , , JS .

+4
1

. ko.mapping, .

, , .

var app = (function (app) {
    app.FilterBooks = function (data) {
        var self = this;
    ko.mapping.fromJS(data, {}, self);

    };
return app;
}(app || {}));

js

<script type="text/javascript">
    $(document).ready(function () {
    var data = @Html.Raw(Json.Encode(Model));
        var e = new app.FilterBooks(data);
        ko.applyBindings(e);
    });
</script>

, @james14, , .

http://knockoutjs.com/documentation/plugins-mapping.html

PM> Install-Package Knockout.Mapping

https://www.nuget.org/packages/Knockout.Mapping

+3

All Articles