How to access and display mapped data with ko.mapping script (Razor page)?

我的未来我决定 提交于 2019-12-25 09:22:31

问题


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>


来源:https://stackoverflow.com/questions/14636135/how-to-access-and-display-mapped-data-with-ko-mapping-script-razor-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!