Search code examples
javascriptc#knockout.jsdata-bindingdotvvm

dotVVM passing values from databinded DOM-elements to javascript vars for visualisation


I am creating a dotVVM webApp for data-visualisation but get a little problem:

Because of the data-binding between my view(html) and my viewModel(c#) i only get knockout comment strings back by those DOM-elements. (dotVVM is using Knockout.js for data-binding)

The var currency gets following value : "<"!-- ko text: Currency --">"<"!-- /ko --">" and is displayed in my input field with id of "1".

I need to get the right value (in this case 40 or initial value 400) into javascript-var for visualisation.

        var currency = document.getElementById("textBox").innerHTML;
        document.getElementById("1").value= currency;
        
 <div ID="container" style="width:100%; height:400px;"></div>

    <p ID="textBox">{{value: Currency}}</p>
    <input ID="1" value="" style="width: 900px" /
    
    

And this is my ViewModel (just as simple as it can be for demonstration purpose)

    /// <summary>
    /// Gets or sets the active page. This is used in the top menu bar to 
    highlight the current menu item.
    /// </summary>
    public virtual string ActivePage => Context.Route.RouteName;

    public int Currency { get; set; } = 400;

    public void currency()
    {                    
            Currency = 40;
    }

Solution

  • First, you can probably use <dot:TextBox Text="{value: Currency}" /> to get a <input type="text"> bound to Currency property.

    If you can't use this and don't want to write your own control, you can access data context as you would in knockout.js - <input type="text" data-bind="value: Currency" /> is the same as the TextBox and you can use ko.dataFor(element) to access view model for the element or ko.contextFor(element) to access knockout context with $parent, $index, ....

    This is how you can get currency in Javascript: var currency = knockout.dataFor(document.getElementById("textBox")).Currency();