问题描述
大家好,
我想显示从数据库获取的数据并存储在ViewBag或TempData中,如下所示:
Hi all,
I want to display data that i get from my database and store in ViewBag or TempData, like this:
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)));
我想使用Razor在表格中显示这些数据。我试过这个:
I want to display this data in a table, using Razor. I tried this:
@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>
}
但没有成功。我可以在下拉列表中显示数据:
@ Html.DropDownList(aa,新的SelectList(ViewBag.BikesResult,Value,Text) ));
我做错了什么?
提前致谢
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
推荐答案
ViewBag.BikesResult = new SelectList(db.Bikes.Where(x => x.Sex.StartsWith(searchparameter.Sex) && x.MinAge < age && x.MaxAge > age), "Id", "Name");
但您尝试转换为List< BikesProj.Models.Bike> ;.
But you tried converting to List <BikesProj.Models.Bike>.
@foreach (var bike in ViewBag.BikesResult as List <BikesProj.Models.Bike>)
{
<option>@bike.Name</option>
}
我不确定因为我不知道你的SelectList类定义。
但我认为下面的代码可以帮到你。
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>
}
如果不起作用,请告诉我你的SelectList类定义。
If it doesn't work, please let me know your SelectList class definition.
这篇关于如何在带有剃刀的表格中显示选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!