下拉框如何从数据库取数据

先获取List

在Controller里面写好获取List,然后通过ViewBag传到视图

ViewBag.testList = _testBll.GettestList();

这样获取到了List集合

视图处理

首先,接收一下

@{
        var testList = ViewBag.testList;
}

然后,写一个HTML标签,使用select标签,value是id,显示的是name

<th>测试下拉框</th>
<td data-title="测试下拉框">
<select id="test" name="test" style=" 150px; height: 23px;">
@foreach (test item in testList)
{
   <option selected="selected" value="@item.id">@item.Name</option>
 }
</select>
</td>

这样是可以了,但是当我编辑的时候,我希望下拉框还是显示出来我以前选择的内容,视图部分更新为下

<select id="test" name="test" style=" 150px; height: 23px;">
@foreach (test item in testList)
{
     <option value="@item.id" @if (item.Name==Model.ProductWarehouse.Name) { <text>selected="selected" </text> }>@item.Name</option>
 }
</select>                                  
  

我是取回了我上次存储的内容,然后判断一下,如果Name一样了,就设置为selected。

原文地址:https://www.cnblogs.com/yunquan/p/10968974.html