Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting initial value of knockout viewmodel using razor

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?

like image 334
Ingó Vals Avatar asked May 10 '26 16:05

Ingó Vals


2 Answers

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.

like image 144
Paul Tyng Avatar answered May 13 '26 14:05

Paul Tyng


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')
like image 42
Mike Gwilt Avatar answered May 13 '26 13:05

Mike Gwilt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!