RJ Uy
RJ Uy

Reputation: 397

How to get the value of a two dimensional array in Razor?

I have a jagged array as shown below, and the array is inside a c# code:

@{
    int[][] array = new int[2][4];
    // codes here that manipulates the values of the array.
}

Now I want to get/traverse to the values in the array. But the code below just don't work. When I run the program I got a run-time error "Index was outside the bounds of the array."

for(var i = 0 ; i < @array.Count(); i++){
    alert( '@array['i'].Length');
}

How to do that?

Thanks

Upvotes: 0

Views: 3663

Answers (3)

David Colwell
David Colwell

Reputation: 2590

try something like

foreach(var subArray in array)
{
   @:alert(subArray.Length);
}

but wont the length always be the same since it is statically declared?

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062745

The only problem I can see there is that the razor itself is a bit... odd; it is not clear whether the alert is intended to be cshtml or output, but the line does not look valid for either.

If alert is output, can you try:

// note this might need to be @for, depending on the line immediately before
for(var i = 0 ; i < array.Length; i++) {
    @:alert('@(array[i].Length)');
}

And if alert is intended as server-side:

// note this might need to be @for, depending on the line immediately before
for(var i = 0 ; i < array.Length; i++) {
    alert(array[i].Length);
}

Upvotes: 0

YD1m
YD1m

Reputation: 5895

Traversing multidimension array:

    int[,] a = new int[,]
    {
        {2, 4}
    };

    for (int i = 0; i <= a.GetUpperBound(0); i++)
    {
        for (int k = 0; k <= a.GetUpperBound(1); k++)
        {
            // a[i, k]; 
        }
    }

Upvotes: 1

Related Questions