Home > Blockchain >  How do I convert this string formatted array to an actual array in C#?
How do I convert this string formatted array to an actual array in C#?

Time:09-10

I am submitting a form to controller, the form consists of properties in which one of them is an array.

$("#parsedQuestions input").val(JSON.stringify(questionsArr));
var formData = JSON.stringify($("#trainingForm").serialize());

        $.ajax({
            type: "POST",
            url: '@Url.Action("SaveTraining", "Training")',
            data:  formData,
            error: function(jqXHR, textStatus, errorMessage) {
                console.log(errorMessage);
            },
            success: function(data) {console.log(data)} 
        });

The questionsArr is the array, but it is being returned as plain string like this

"[["1","11","111","1111","1111","11111"],["1","22","222","2222","22222","2222222"]]"

My Controller

public async Task<IActionResult> SaveTraining([FromForm] KII_TrainingModel formData)
{
}

It's a 2 dimensional array supposedly.

In my model I tried to make this property ParsedQuestions as string[][] and List. But I only get one element, which is the formatted string array.

I have looked everywhere to find a solution but can't find one. Any answers or idea will be appreciated.

If I don't stringy it, it looks like this enter image description here

If I do, then it returns this "[["1","11","111","1111","1111","11111"],["1","22","222","2222","22222","2222222"]]"

Any suggestions even as to how to convert this string to an actual array?

CodePudding user response:

I believe that the way that sets the array into the text field and retrieves it from the form, the array will be in string value.

Instead, you have to append the array into formData via FormData.append() similar to below:

for (let i = 0; i < questionsArr.length; i  ) {
    for (let j = 0; j < questionsArr[i].length; j  ) {
        formData.append(`ParsedQuestions[${i}][${j}]`, questionsArr[i][j]);
    }
}

And this line is no longer needed:

$("#parsedQuestions input").val(JSON.stringify(questionsArr));

CodePudding user response:

I wrote this as a sample: you can access the data indexing into both arrays.

    let ar = [["1", "11", "111", "1111", "1111", "11111"], ["1", "22", "222", "2222", "22222", "2222222"]]
let ans =    ar[0][2];
console.log(ans);

  • Related