I'm still new to Knockout and Javascript and have searched the web but can not find a solution for the problem that I have the following javascript in an asp.net page.
What I am trying to achieve is to send a object array of client to the asp.net page method "saveClients",how do I recieve the object array in my C# code in the asp.net page ? And then how do I send an object array back to the javascript function "loadClients"
THis is the javascript inside my html page
function client(_name, _age) {
return {
name: ko.observable(_name),
age: ko.observable(_age)
}
};
var vm = {
clients: ko.observableArray(),
addClient: function () {
this.clients.push(new client(document.getElementById("inputName").value, document.getElementById("inputAge").value));
},
saveClientsEvent: function () {
saveClients();
},
loadClientsEvent: function(){
loadClients();
}
}
function saveClients() {
var d = {
clients: vm.clients()
}
$.ajax({
type: "POST",
url: "jumpStart.aspx/saveClients",
data: JSON.stringify(d),
dataType: "JSON",
contentType: "application/json",
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
}
function loadClients() {
$.ajax({
type: "POST",
url: "jumpStart.aspx/loadClients",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.d.age);
},
error: function (result) {
alert("error");
}
});
}
$(document).ready(function () {
ko.applyBindings(vm);
});
This is the code behind in my asp.net page.
[System.Web.Services.WebService]
public partial class jumpStart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string saveClients(object[] clients)
{
return "Hello";
}
[System.Web.Services.WebMethod]
public static client[] loadClients()
{
client[] clients = new client[2];
clients[0] = new client{name="Freddie",age="28"};
clients[1] = new client { name = "Fanie", age = "28" };
return clients;
}
public class client
{
public string name { get; set; }
public string age { get; set; }
}
}
Sending a string or int to the page and back is easy but how do you send and parse an object array ?
Any help would be appreciated.