0

I have a 2D Array declared in my MVC Controller, and I need to access this via Razor so I can loop through each value.

I create a session and set it as the array, but I can't figure out how to access the array through razor.

Controller:

string[,] Things = new string[,] {
            { "thing1", "pie" },
            { "thing1", "cake" },
            { "thing1", "potato" }
        };

public void GetThings()
{
    Session["Things"] = Things;
}

public ActionResult Index()
{
    GetThings();
    return View();
}

Razor:

@{
    for (int i = 0; i < Session["Things"].GetLength(0); i++)
    {
        @i
    }
}

I get the error "'object' does not contain a definition for Getlength, the only suggested actions are .Equals, .GetHashCode, .GetType, and .ToString.

The above c# in the razor works if I declare the array within the razor, replacing "Session..." with the array variable name.

I can't read any values from the array session to display on the HTML front end, doing @Session["Things"] displays System.String[,] in browser (but then this is the same as if I tried to call the array declared in razor), @Session["Things"][1,1] gives browser error

Cannot apply indexing with [] to an expression of type 'object'

4
  • Session holds objects not strongly typed, hence the error "Cannot apply indexing with [] to an expression of type 'object'" Commented Jan 7, 2019 at 16:37
  • 1
    Possible duplicate of How to use Session variable object in foreach-MVC5 View Commented Jan 7, 2019 at 16:39
  • Why would you use a session for this? Commented Jan 8, 2019 at 2:10
  • @ErikPhilips I chose to use a session as this array needs to be used in multiple places not just in the razor front end, such as other functions in the controller and called through a get to JS (as JSON), and I didn't want to have to repeat this array in multiple places. This way means I have one master list I need to manage, and couldn't think of a better way to declare the array once and have it accessible by all areas that need it. If theres a better way please let me know :) Commented Jan 8, 2019 at 9:02

1 Answer 1

1

Cast to array:

((string[,])Session["Things"]).GetLength(0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.