我已经尝试了所有方法,友好的URL解析,关于webmethod的enable session等,但是无论如何都无法解决。请解决我的这个问题。
这是我用于插入和删除员工的HTML代码
<table>
<thead>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Salary</th>
</thead>
<tbody style="color:white" data-bind="foreach:Employees">
<tr>
<td> <span data-bind="text: ID"></span> </td>
<td> <span data-bind="text: Name"></span></td>
<td> <span data-bind="text: Salary"></span></td>
<td> <button type="button" data-bind="click: $parent.DeleteRecord"> Delete</button></td>
</tr>
</tbody>
</table>
<hr />
</div>
<h2> Add New Employee</h2>
<div style="background-color:wheat">
<table>
<tr>
<td>Employee ID:</td>
<td><input type="text" data-bind="value:ID" /></td>
<td><span data-bind="text: ID"></span></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><input type="text" data-bind="value: Name" /></td>
<td><span data-bind="text: Name"></span></td>
</tr>
<tr>
<td>Employee Salary:</td>
<td><input type="text" data-bind="value:Salary"/></td>
<td><span data-bind="text: Salary"></span></td>
</tr>
<tr>
<%-- <td><button type="submit" data-bind="click:$root.checkfunc">Check</button></td>--%>
<td><button type="submit" data-bind="click:insert"> Add Employee </button></td>
</tr>
</table>
</div>
这是我的带有敲除和ajax的Jquery脚本:
<script>
function Employee(emp)
{
this.ID= ko.observable(emp.ID)
this.Name = ko.observable(emp.Name);
this.Salary = ko.observable(emp.Salary);
}
function employeeviewModel() {
var self = this;
self.ID = ko.observable();
self.Name = ko.observable();
self.Salary = ko.observable();
self.Employees = ko.observableArray();
self.insert = function () {
var jsondata = Employee({ ID: self.ID(), Name: self.Name(), Salary: self.Salary() });
$.ajax({
type: "POST",
url: "Testing.aspx/insertEmployee",
contentType: "application/json; charset=utf-8",
dataType:"json",
data: '{employee: ' + JSON.stringify(jsondata) + '}',
success: function (data) {
self.Employees.push(new Employee({ ID: self.ID(), Name: self.Name(), Salary: self.Salary() }));
alert(data.d);
},
error: function (data) {
alert(data);
}
});
};
self.DeleteRecord = function (data) {
self.Employees.remove(data);
};
}
$(document).ready(function () {
var mymodel = new employeeviewModel();
ko.applyBindings(mymodel);
});
</script>
这是我的代码背后的代码:
[WebMethod]
public static Employee insertEmployee(Employee data)
{
EmployeeRepository repository = new EmployeeRepository();
repository.Add(data);
return data;
}
[WebMethod]
public static void deletenow(int id)
{
EmployeeRepository repository = new EmployeeRepository();
repository.delete(id);
}
最佳答案
只需传递这样的参数,就解决了我的问题。如果您将不提供正确格式的参数,则不会调用web方法。
data: JSON.stringify({'employee': jsondata})