如何从jquery ajax调用更新KnockOutJs ViewModel?

时间:2016-07-22 21:36:21

标签: jquery knockout.js

正如您从片段中看到的那样。我想在btnSumbit点击后更新ViewModel的isShowMsg和showMessageValue。 MVC上的控制器基本上返回一个json(fullName)。如何更新已经从jquery ajax调用绑定的viewmodel?

<script type="text/javascript">

    $(document).ready(function () {

        var ViewModel = function (first, last, isshowmsg, showmsg) {
            this.firstName = ko.observable(first);
            this.lastName = ko.observable(last);
            this.isShowMsg = ko.observable(isshowmsg);
            this.showMessageValue = ko.observable(showmsg);
        };
                                      
        $("#btnSubmit").click(function () {

            var firstName = $("#txtFirstName").val();
            var lastName = $("#txtLastName").val();

            $.ajax({
                url: '@Url.Action("Submit","Home")',
                type: "POST",
                data: { firstName: firstName, lastName: lastName },
                dataType: "json",
                success: function (response) {                    
                    if(response.fullName != undefined || response.fullName != null)
                    {
                        ViewModel.isShowMsg = true;
                        ViewModel.showMessage = response.fullName;                        
                    }
                }
            });
        });

        ko.applyBindings(new ViewModel("Planet", "Earth", false, ""));
        
    });

</script>
<style>
    body { font-family: arial; font-size: 14px; }
    .liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
    .liveExample input { font-family: Arial; }
    .liveExample b { font-weight: bold; }
    .liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
    .liveExample select[multiple] { width: 100%; height: 8em; }
    .liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }
</style>
<div class="col-md-12">

            <div class='liveExample'>
                <p>First name: <input id="txtFirstName" data-bind='value: firstName' /></p>
                <p>Last name: <input id="txtLastName" data-bind='value: lastName' /></p>                
                <label id="lblResult" data-bind="visible: isShowMsg, value: showMessageValue"></label>
            </div>

            <button id="btnSubmit">Submit</button>

        </div>

2 个答案:

答案 0 :(得分:2)

你需要放弃jQuery来编写好的Knockout代码。如果您使用的是jQuery选择器,那么您可能做错了什么。有关如何处理点击事件,请参阅the click binding docsKnockout tutorial也非常值得您花时间。

您已为视图模型创建了构造函数ViewModel,但之后您将其视为视图模型本身。 ViewModel.isShowMessage不存在。您需要将视图模型分配给变量,以便可以引用它。此外,observables是setter / getters。要分配值,您需要将其作为参数传递。

var vm = new ViewModel("Planet", "Earth", false, "");
ko.applyBindings(vm);
...and elsewhere...
vm.isShowMessage(true);

答案 1 :(得分:0)

试试这样:

ViewModel.isShowMsg(true);
ViewModel.showMessage(response.fullName);

请参阅the docs on observables