jQuery KnockoutJS,在ajax调用后更新ViewModel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4529057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:24:48  来源:igfitidea点击:

KnockoutJS, updating ViewModel after ajax call

asp.netjqueryasp.net-mvc-3knockout.js

提问by Galen

I am using Knockout and the Knockout Mapping plugin.

我正在使用 Knockout 和 Knockout Mapping 插件。

  • My MVC3 Action returns a View and not JSON directly as such I convert my Model into JSON.
  • This is a data entry form and due to the nature of the system validation is all done in the Service Layer, with warnings returned in a Response object within the ViewModel.
  • The initial bindings and updates work correctly its the "post-update" behavior that is causing me a problem.
  • 我的 MVC3 操作直接返回一个视图而不是 JSON,因此我将我的模型转换为 JSON。
  • 这是一个数据输入表单,由于系统验证的性质,所有验证都在服务层完成,警告在 ViewModel 内的 Response 对象中返回。
  • 初始绑定和更新正常工作,这是导致我出现问题的“更新后”行为。

My problem is after calling the AJAX POST and and receiving my JSON response knockout is not updating all of my bindings... as if the observable/mappings have dropped off

我的问题是在调用 AJAX POST 并且接收到我的 JSON 响应淘汰后没有更新我的所有绑定......好像可观察/映射已经下降

If I include an additional ko.applyBindings(viewModel); in the successthings do work... however issues then arise with multiple bindings and am certain this is not the correct solution.

如果我包含一个额外的 ko.applyBindings(viewModel); 在成功的情况下,事情确实有效……但是,多个绑定会出现问题,并且我确信这不是正确的解决方案。

This is the HTML/Template/Bindings

这是 HTML/模板/绑定

<!-- Start Form -->
<form action="@Url.Action("Edit")" data-bind="submit: save">
<div id="editListing" data-bind="template: 'editListingTemplate'"></div>
<div id="saveListing" class="end-actions">
    <button type="submit">Save Listings</button>
</div>
</form>
<!-- End Form -->

<!-- Templates -->
<script type="text/html" id="editListingTemplate">
        <div class="warning message error" data-bind="visible: Response.HasWarning">
            <span>Correct the Following to Save</span>
            <ul>
                {{each(i, warning) Response.BusinessWarnings}}
                    <li data-bind="text: Message"></li>
                {{/each}}
            </ul>
        </div>

        <fieldset>
            <legend>Key Information</legend>
            <div class="editor-label">
                <label>Project Name</label>
            </div>
            <div class="editor-field">
                <input data-bind="value: Project_Name" class="title" />
            </div>            
        </fieldset>        
</script>
<!-- End templates -->

And this is the Knockout/Script

这是淘汰赛/脚本

<script type="text/javascript">
        @{ var jsonData = new HtmlString(new JavaScriptSerializer().Serialize(Model)); }

        var initialData = @jsonData;
        var viewModel = ko.mapping.fromJS(initialData);


        viewModel.save = function () 
        {
            this.Response = null;
            var data = ko.toJSON(this);
            $.ajax({
                url: '@Url.Action("Edit")',
                contentType: 'application/json',
                type: "POST",
                data: data,
                dataType: 'json',
                success: function (result) {
                ko.mapping.updateFromJS(viewModel, result);
            }
        });
    }

    $(function() {                        
        ko.applyBindings(viewModel);            
    });
</script>

And this is the response JSON returned from the successful request including validation messages.

这是从成功请求返回的响应 JSON,包括验证消息。

{
    "Id": 440,
    "Project_Name": "", 
    "Response": {
        "HasWarning": true,
        "BusinessWarnings": [
            {
                "ExceptionType": 2,
                "Message": "Project is invalid."
            }, {
                "ExceptionType": 1,
                "Message": "Project_Name may not be null"
            }
        ]
    }   
}

UPDATE

更新

Fiddler DemoIs a trimmed live example of what I am experiencing. I have the Project_Name updating with the returned JSON but the viewModel.Response object and properties are not being updated through their data bindings. Specifically Response.HasWarning().

Fiddler Demo是我所经历的修剪过的现场示例。我使用返回的 JSON 更新了 Project_Name,但是 viewModel.Response 对象和属性没有通过它们的数据绑定进行更新。特别是 Response.HasWarning()。

I've changed back to ko.mapping.updateFromJS because in my controller I am specifically returning Json(viewModel).

我已经改回 ko.mapping.updateFromJS 因为在我的控制器中我专门返回 Json(viewModel)。

Cleaned up my initial code/question to match the demo.

清理了我的初始代码/问题以匹配演示。

采纳答案by Gelin Luo

I guess Response is reserved, when I change "Response" to "resp", everything went fine. See http://jsfiddle.net/BBzVm/

我猜响应是保留的,当我将“响应”更改为“响应”时,一切正常。见http://jsfiddle.net/BBzVm/

回答by Bcelik

Should't you use ko.mapping.updateFromJSON on your success event? Chapter Working with JSON stringson Knockout Mapping site says:

您不应该在成功事件中使用 ko.mapping.updateFromJSON 吗?在 Knockout Mapping 站点上使用 JSON 字符串一章说:

If your Ajax call returns a JSON string (and does not deserialize it into a JavaScript object), then you can use the functions ko.mapping.fromJSON and ko.mapping.updateFromJSON to create and update your view model instead.

如果您的 Ajax 调用返回一个 JSON 字符串(并且没有将其反序列化为 JavaScript 对象),那么您可以使用函数 ko.mapping.fromJSON 和 ko.mapping.updateFromJSON 来创建和更新您的视图模型。