问题描述
我在数据库中的表有字段:Id
,Organisation
,Info
.
My table in db have fields : Id
,Organisation
,Info
.
我想制作这样的下拉列表:
I want make dropdowm list like that:
<select>
<option value='Id there'>'Organisation there'</option>...
我正在尝试使用 ViewBag:
I'm try to do it, using ViewBag:
ViewBag.Organisations = db.Organisations.ToList(); // get all fields from table using dbContext
并在视图中:
@Html.DropDownList('I don`t know what i shoud write here, please help')
我如何建立下拉列表?
推荐答案
您需要创建一个 SelectList
在控制器操作中使用 构造函数 可用,在视图中只需将 DropDownList 方法作为参数传递即可.
You would need to create a SelectList
in controller action using one of the constructors available and in view just pass it DropDownList method as parameter.
在控制器中这样做:
ViewBag.Organisations = new SelectList(db.Organisations.ToList(),"Id","Organisation");
在SelectList
中,我们需要在option
中指定哪个属性用作value
,哪个用作text
我们在最后两个参数中指定的 code> 标签.
in SelectList
we need to specify which property to use as value
and which to use as text
in the option
tag which we are specifying in last two parameters.
然后在视图中你需要这样使用它:
and then in View you would need to use it this way:
@Html.DropDownList("Organization",ViewBag.Organisations as SelectList)
这里第一个参数将用作 select
元素的名称,第二个参数将用于填充 select
中的 option
元素
Here first parameter would be used as name of select
element and second one will be used to populate the option
elements in the select
以下是可用于 Html.DropDownList
的重载列表:
Following is the list of overloads available for Html.DropDownList
:
这篇关于使用 ViewBag 的 Asp.net mvc 下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!