Возьмите значения из массива с помощью WebMethod - PullRequest
0 голосов
/ 06 июня 2018

У меня есть следующий массив jquery, который берет значения из двух столбцов из моей таблицы и показывает их значения:

$(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);
                     }
                 });
             });
         });

Имя первого столбца - «label», а имя второго - «opis».'результат массива в консоли:

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

Значения принимаются с помощью этого нажатия кнопки:

<button id="myButton"  type="button">Save</button>

Ajax (статус 200) принимает и POST правильно значения 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

Может кто-нибудь помочь мне с частью C #?Мне нужен WebMethod для получения значений из ajax, чтобы я мог отправить его в базу данных или просто помочь мне прочитать значения в c #.

Заранее спасибо!

1 Ответ

0 голосов
/ 06 июня 2018

Убедитесь, что ваш ajax получил параметр и значение в данных

        $.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);
                 }
             });

Создайте класс модели с двумя свойствами: label, opis Примечание. Свойства должны иметь те же имена, что и свойства массива ajax.

public class myCollection
{
    public String label{ get; set; }
    public String opis{ get; set; }
}

Теперь создайте WebMethod в codebehind с параметром типа List :

[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";
}

Спасибо.

...