Reputation: 371
I have following jquery array, that takes the values from two columns from my table and show's their values:
$(function () {
$('#myButton').on('click', function () {
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function () {
var row = this;
var myObj = {
label: valuefromType($(row).find($(row).find('td:eq(1)').children())),
opis: valuefromType($(row).find($(row).find('td:eq(2)').children()))
};
myCollection[myCollection.length] = myObj;
});
console.log(myCollection)
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
break;
case "span":
return $(control).text();
break;
case "select":
return $(control).val();
break;
}
}
$.ajax({
type: "POST",
url: "FirstPage.aspx",
//data: { obj: myCollection },
data: JSON.stringify(myCollection),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
});
Name of the first column is 'label' and name of the second is 'opis' result of the array in console:
myCollection
(6) […]
0: Object { label: "1", opis: "Test1" }
1: Object { label: "2", opis: "Test2" }
2: Object { label: "3", opis: "Test3" }
3: Object { label: "5", opis: "1" }
4: Object { label: "9", opis: "Test5" }
5: Object { label: "15", opis: "Test6" }
length: 6
Values are taken with this button click:
<button id="myButton" type="button">Save</button>
Ajax(status 200) takes and POST's the values correctly JSON:
0 {…}
label 1
opis test1
1 {…}
label 2
opis test2
2 {…}
label 3
opis test3
3 {…}
label 5
opis 1
4 {…}
label 9
opis test5
5 {…}
label 15
opis test6
Can someone help me with the C# part ? I need WebMethod to take the values from ajax so I can send it to the database, or just help me read the values in c#.
Thanks in advance !
Upvotes: 0
Views: 267
Reputation: 26
Make sure your ajax got parameter and value in data
$.ajax({
type: "POST",
url: "FirstPage.aspx",
data: JSON.stringify({'omyCollection': myCollection}), // Check this call.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
Create a model class with two properties: label,opis Note: The properties should have the same names as the ajax array's properties.
public class myCollection
{
public String label{ get; set; }
public String opis{ get; set; }
}
Now create a WebMethod in codebehind with a parameter of type List< myCollection >:
[WebMethod(EnableSession = true)]
public static string GetCollection(List<myCollection> omyCollection)
{
foreach (myCollection mycol in omyCollection)
{
string id = mycol.label; //access label from myCol object
string opis = mycol.opis;
//do something
}
return "response";
}
Thanks.
Upvotes: 1