我正在使用自动完成将名称添加到表行的动态列表中。当我添加一个新名称时,会创建一个新行,但不会更新 searchText 和 searchId。删除链接似乎有效。所以我的观点看起来像;
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SHP.Models.TrainingListEmployeesViewModel>" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Bulk Training
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form class="employeeListEditor">
<h3>Allocate or cancel training for the selected employees</h3>
<table>
<tr>
<td style="text-align: right;">Course Name</td>
<td><%: Html.EditorFor(model => model.TrainingName) %></td>
</tr>
<tr>
<td style="text-align: right;">Description (optional)</td>
<td><%: Html.TextAreaFor(
model => model.TrainingDescription, new { maxlength = "255", style = "width:400px;height:100px;" }) %></td>
</tr>
</table>
<%: Html.EditorFor(model => model.ClientEmployeeSelector) %>
<button data-bind="click: addEmployee">Add</button>
<%--<input type="hidden" name="numberOfEmployees" id="numberOfEmployees" value="<%:Model.EmployeeList.Count %>" />--%>
<div id="displayEmployees" style="margin-top:10px;display: block">
<table id="employeeDataTable" class="groupBorder">
<thead>
<tr>
<th></th>
<th>Employee</th>
</tr>
</thead>
<tbody data-bind="foreach: employees">
<tr>
<td>
<a href="#" data-bind="click: $parent.removeEmployee">Remove</a>
<input type="hidden" data-bind="value: searchId"/>
</td>
<td><span data-bind="text: searchText"></span></td>
</tr>
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
function Employee(id, text) {
var self = this;
self.searchId = id;
self.searchText = text;
}
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
function ViewModel() {
var self = this;
self.employees = ko.observableArray(initialData.EmployeeList);
self.searchText = ko.observable(initialData.SearchText);
self.searchId = ko.observable(initialData.SearchTextId);
self.removeEmployee = function(employee) {
self.employees.remove(employee);
};
self.addEmployee = function() {
self.employees.push(new Employee(self.searchId, self.searchText));
$('#SearchText').val('');
};
self.save = function() {
ko.utils.postJson(location.href, { employees: self.employees });
};
}
ko.applyBindings(new ViewModel());
</script>
</asp:Content>
当我单击添加按钮时(我希望在它工作时将其删除,以便由返回键触发添加事件)以下行被添加到表中;
<tbody data-bind="foreach: employees">
<tr>
<td>
<a href="#" data-bind="click: $parent.removeEmployee">Remove</a>
<input type="hidden" data-bind="value: searchId" value=""/>
</td>
<td><span data-bind="text: searchText"/></td>
</tr>
</tbody>
因此出现正确的删除链接并且它也可以正常工作。但是 searchId 和 searchText 都没有设置。我究竟做错了什么?