3
votes

I'm finding it strange that I can't find any information about how to populate the Knockout viewmodel dynamically. I guess my search terms are incorrect or something.

Anyways as I'm using Asp.Net MVC 3 and am only going to use knockout for one specific page this first time I was hoping I could somehow use the Razor model to insert into the knockout.

@Html.TextBoxFor(m => m.PropertyName, new { data_bind = "value: name" })

I figured that this didn't work because even if the razor populates the field with the PropertyName it happens before the binding so it doesn't force it's value to the knockout viewmodel.

        var viewModel = {
        name: ko.observable(@GetPoertyNameUsingRazorSomehow)
    };

This doesn't work either, at least not in anyway I understand.

As we can easily get RazorModel data using MVC 3 normally I was sure we somehow could inject it into the Knockout viewModel. I haven't seen any tutorials that explain how. What am I missing?

2

2 Answers

4
votes

I created a little library on top of Json.NET for just such an occasion:

https://github.com/paultyng/FluentJson.NET

You can create JSON in a Razor view like this (note the Knockout extension methods):

@JsonObject.Create()
    .AddProperty("name", "value")
    .AddProperty("childObject", c => {
        .AddProperty("childProperty", "value2")
    })
    .AddObservable("knockoutProperty", 123)

This would produce JSON similar to this:

{"name":"value","childObject":{"childProperty":"value2"},"knockoutProperty":ko.observable(123)}

The Knockout methods are added via extension methods and other things can easily extend as well.

The package is on Nu-Get if you want it.

3
votes

Assuming your property name should be a string, this should work if you enclose @GetPoertyNameUsingRazorSomehow in quotes. Otherwise, you're passing an undefined object into the observable.

name: ko.observable('@GetPoertyNameUsingRazorSomehow')