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?

  • @Icarus I am passing the array from controller to view. I'm confused where you are getting lost. Maybe I can explain more? – Luke Danger Kozorosky Jun 14 '17 at 18:17
  • if the viewdata is a list, should it not be acced via index `@ViewData["ids"][i]`? – lloyd Jun 14 '17 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[]. – Luke Danger Kozorosky Jun 19 '17 at 13:41

1 Answers1

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?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61