How to access and display mapped data with ko.mapp

2019-09-06 11:26发布

问题:

Java script (getting data using Can`t get json object to with knockout answer {1} method):

<script type="text/javascript">
    $.getJSON("/api/TelemarketingApi", function (result) {
        function viewModel() {            
            return ko.mapping.fromJS(result);
        };
        ko.applyBindings(new viewModel());
    })
    .error(function () { alert("error"); });
</script>

JSON object:

[
    {
        "TelemCalls": [ {"ID": 1, "duratio": "11"}],
        "ID": 1,
        "FirstName": "Jonas",
        "LastName": "Jonaitis",
        "Phone": "860123123",
        "Municipality": null
    }
]

How can I access and display mapped JSON data in a razor page?

回答1:

Do you have the viewModel mapped from the json object and binded to entire razor view. To display values in the razor view only has to create html elements bound to the viewModel like this:

<input type="text" data-bind="value: ID" />
<input type="text" data-bind="value: FirstName" />
<input type="text" data-bind="value: LastName" />
<input type="text" data-bind="value: Phone" />
<input type="text" data-bind="value: Municipality" />

Example in Fiddle: http://jsfiddle.net/vfportero/hcVmZ/



回答2:

Remember that your mapped data is accessible only in JavaScript, not on the server side while page is being built by Razor. So to show viewModel's property values on the page try the following:

<input data-bind="value: FirstName" />
<ul data-bind="foreach: TelemCalls">
    <li data-bind="text: duratio"></li>
</ul>

If your top-level viewmodel is an array so use the following syntax:

<div data-bind="$data">
    <input data-bind="value: FirstName" />
    <ul data-bind="foreach: TelemCalls">
        <li data-bind="text: duratio"></li>
    </ul>
</div>