What is the best practice to get MVC Model parameters within knockout Model?
1) If you need to get just one parameter, you can use the following to set up knockout view model property:
this.firstName = @Model.FirstName;
2) If you have a bunch of properties wihtin a model, you can do the following:
var modelData = function () { return @Html.Raw(Json.Encode(Model)); }();
and then later use
this.firstName = modelData.FirstName;
this.lastName = modelData.LastName;
this.phoneNumber = modelData.PhoneNumber;
etc.
3) What if you have some Collection within Person model. What is the best way to get the collection out of the person model?
For example, Person has FirstName, LastName, PhoneNumber etc. and has a List of Books (each book has tile, author and other properties).
I believe you can use seomething like this:
var booksJSON = @Html.Raw(Json.Encode(Model.Books));
and then in the knockout Person model use:
self.books = ko.observableArray(booksJSON);
This gives only Books.
But what if I want to get all information about Person (Books, including FirstName, LastName, Phone and a bunch of properties), what is the best way to do this? Can I somehow use Json.Encode
for the whole Person model and then get out of there everything, including Person.Books or should I split it into multiple Json.Encode-s
??
If you want to make a simple (one-way) binding, this will do
But if you want a two-way binding, ie, you wanna post back changes to the existing array back to server, you wanna make all properties in the object array
ko.observable
. That's because, as per knockoutjs documentation,To make each object properties in the array
ko.observable
, we can use this generic function.Now we can use the function like this.
All data what you need should be in your C# Model. Then in knockout viewModel you should parse this data. For example:
C#
Html, you should convert your C# model to json:
Knockout viewModel: