Wie Sie aus dem Schnipsel sehen können. Ich möchte das ViewModel isShowMsg und showMessageValue nach dem Klick auf btnSumbit aktualisieren. Der Controller auf MVC gibt im Grunde eine json (fullName) zurück. Wie aktualisiere ich ein Viewmodel, das bereits von jquery ajax call gebunden ist?Wie aktualisierst du ein KnockOutJs ViewModel von einem Jquery Ajax Aufruf?
<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>
Ich habe "ViewModel.isShowMsg ist keine Funktion". – Jack
Sie könnten das ViewModel anstelle einer Funktion (oder einer selbstausführenden Funktion) als json-Objekt definieren. Und was ich gerade bemerkt habe, auf ko.applyBindings passierst du nicht das oben definierte Viewmodel. – Zbrr