我的应用程序是MVC 5 c#,我使用以下表格来更新表格:
@using (Ajax.BeginForm("AddOha", "Medication", new AjaxOptions()
{
UpdateTargetId = "result",
OnSuccess = "getresult",
HttpMethod = "POST"
}))
{
<input id="MedName" name="MedName" value="" class="input-sm form-control" style="width: 100px" placeholder="Value"/>
<input type="submit" value="Save" class="btn btn-primary"/>
}
这是我的淘汰赛名单:
<tbody data-bind="foreach: OhaList">
<tr>
<td>
<input data-bind="value: Name" class="input-sm form-control" style="width: 100px" placeholder="Value" />
</td>
</tr>
</tbody>
这是ViewModel:
var ViewModel = function() {
var self = this;
this.OhaList = ko.observableArray([]),
$.ajax({
type: "GET",
url: '@Url.Action("xxx", "xxx")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.OhaList(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
var ohaMed = {
Name: self.Name
};
self.ohaMed = ko.observable();
}
ko.applyBindings(new ViewModel());
我尝试使用以下方式更新列表:
var getresult = function(data) {
if (data[0].Name !== "") {
// alert(data[0].Name);
ViewModel.OhaList.push({ Name: data[0].Name });
// ViewModel.OhaList.push({ Name: "1});
} else {
alert("failed");
}}
虽然我从控制器获得结果,或者即使我对值进行编码,但我收到以下错误:
Unable to get property 'push' of undefined or null reference
非常感谢您的建议。
答案 0 :(得分:1)
You need to keep a reference to your viewmodel handy, here's one way to do that:
window.viewModel = new ViewModel();
ko.applyBindings(window.viewModel);
Then in your getresult function, you need to use that instance of ViewModel to push the values to, rather than the ViewModel type itself:
var getresult = function(data) {
if (data[0].Name !== "") {
// alert(data[0].Name);
window.viewModel.OhaList.push({ Name: data[0].Name });
// ViewModel.OhaList.push({ Name: "1});
} else {
alert("failed");
}
}