0

I'm passing a Stored Procedure into my Controller, which I then want to send to my View and log each entry of the Stored Procedure into a dropdown menu. My problem is that when I pass the data over to the dropdown menu, all I get is System.String[] instead of the actual value.

Controller:

public ActionResult Dropdown()
{
    ViewData["ids"] = db.uspGetAllEventIds().ToArray();
    return View();
}

View:

@model IEnumerable<Heatmap.Models.Event>
...
<body>
    <div>
        <select name="EventId">
            @for (var i = 0; i < 6; i++)
            {

                <option>@ViewData["ids"]</option>
            }
        </select>

    </div>
</body>

Right now I only have a simple for loop set to 6, but I want to iterate through my entire ids array (which should be filled with the values from db.uspGetAllEventIds() and enter them into my dropdown menu. How should I set my loop up to do this?

3
  • @Icarus I am passing the array from controller to view. I'm confused where you are getting lost. Maybe I can explain more? Commented Jun 14, 2017 at 18:17
  • if the viewdata is a list, should it not be acced via index @ViewData["ids"][i]? Commented Jun 14, 2017 at 22:48
  • @lloyd Yes that's what I thought too. I don't remember exactly why that didn't work (I haven't looked at it since last Wednesday) but it was either a compiler error or returning System.String[]. Commented Jun 19, 2017 at 13:41

1 Answer 1

1

To use a string array inside ViewData object, you need to cast ViewData into string[] with as operator (or simply a direct casting if you're sure not throwing exception) and later iterate the contents as shown in code below:

@model IEnumerable<Heatmap.Models.Event>
...
<body>
    <div>
        <select name="EventId">
            @{
                // a simple (string[])ViewData["ids"] also work here
                var ids = ViewData["ids"] as string[];
                for (var i = 0; i < 6; i++) 
                {
                    <option>@ids[i]</option>
                }
             }
        </select>
    </div>
</body>

Working example: .NET Fiddle Demo

NB: You can't access array elements using ViewData["ids"][i] inside for loop because ViewData is a dynamic dictionary which has object type, not object[].

Tip: If you want to iterate through entire ids array, use ids.Length as upper limit value in for loop after casting ViewData.

Reference:

ASP.NET MVC - How to pass an Array to the view?

How to pass an array from Controller to View?

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you so much! Sorry for the delayed response, I took an early weekend xD

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.