GRU119
GRU119

Reputation: 1128

Loop through multiple models in MVC 5 using razor

I'm setting a ViewData.Model that gets populated from a a data table. In my View, I'm looping through the ViewData.Model displaying the data. I'm trying to create a second ViewData.Model and do the same thing. How do I accomplish this? I have the code to the first ViewData.Model that is working. If you keep looking below, I have my attempt at setting the second ViewData.Model but I'm unable to display the data in the view...

Controller with working ViewData.Model

var dataTable = new DataTable();
dataTable.Load(reader);
ViewData.Model = dataTable.AsEnumerable();

View with working ViewData.Model

@foreach (var item in ViewData.Model)
{
   @item["ACCT_ID"]
}

Controller with second ViewData.Model

var dataTable = new DataTable();
dataTable.Load(dataReader);
ViewData["scheduledDate"] = dataTable.AsEnumerable();

View pulling with second ViewData.Model but doesn't work

@foreach (var item in ViewData["scheduledDate"] )
{
    @item["DATE_ID"]
}

Update - Working second ViewData.Model Thanks to @teo van kot , i'm now able to display content with my 2nd ViewData.Model. Here is the code in my view that works...

 @foreach (var item in (IEnumerable<System.Data.DataRow>)ViewData["scheduledDate"])
    {
        @item["DATE_ID"]
    }

Upvotes: 0

Views: 1334

Answers (1)

teo van kot
teo van kot

Reputation: 12491

You should cast your model to your Type if you using ViewData.

Like this:

@foreach (var item in (IEnumerable<YourType>)ViewData["scheduledDate"] )
{
    @item["DATE_ID"]
}

Only change YourType to type that you actually have and this will work

Upvotes: 2

Related Questions