Click here to Skip to main content
15,892,517 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I want to display data that i get from my database and store in ViewBag or TempData, like this:

SQL
ViewBag.BikesResult = new SelectList(db.Bikes.Where(x => x.Sex.StartsWith(searchparameter.Sex) && x.MinAge < age && x.MaxAge > age), "Id", "Name");
                TempData.Add("BikeResults", new SelectList(db.Bikes.Where(x => x.Sex.StartsWith(searchparameter.Sex) && x.MinAge < age && x.MaxAge > age)));


I want to display this data in a table, using Razor. I tried this:

SQL
@if (ViewBag.BikesResult != null)
        {
         <table>
             <tr>
                 <td>
                     <h3>Bike</h3>
                 </td>
                 <td>
                     <select id="sltBike">
                        <option>Bikes Result 
                         </option>                       
                            @foreach (var bike in ViewBag.BikesResult 
                            as List <BikesProj.Models.Bike>)
                            {         
                                 <option>@bike.Name</option>            
                            }
                     </select>
                 </td>
             </tr>
         </table>
        
        }


But with no sucess. I can display the data in a dropdown like this:

@Html.DropDownList("aa", new SelectList(ViewBag.BikesResult, "Value", "Text"));

What am I doing wrong?

Thanks in advance
Posted

1 solution

Type is wrong. You made instance of SelectList here.

ViewBag.BikesResult = new SelectList(db.Bikes.Where(x => x.Sex.StartsWith(searchparameter.Sex) && x.MinAge < age && x.MaxAge > age), "Id", "Name");


But you tried converting to List <BikesProj.Models.Bike>.

@foreach (var bike in ViewBag.BikesResult as List <BikesProj.Models.Bike>)
{         
     <option>@bike.Name</option>            
}


I am not sure becaouse I don't know about your SelectList class definition.
But I think that below code may help you.

@foreach (var bike in ViewBag.BikesResult as SelectList)
{         
     <option>@bike.Name</option>            
}


If it doesn't work, please let me know your SelectList class definition.
 
Share this answer
 
v2
Comments
Eduardo Cardoso 27-Aug-14 5:43am    
Hi David,

It worked! Many thanks! I tried so many things that my code got confused, that List <bikesproj.models.bike> model was from one of my tries.
David Lee 145 27-Aug-14 5:46am    
Good!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900