使用ViewBag的ASP.NET MVC下拉列表 [英] Asp.net mvc dropdown list using ViewBag
问题描述
我在db中的表具有字段:Id
,Organisation
,Info
.
My table in db have fields : Id
,Organisation
,Info
.
我想要像这样放置dropdowm列表:
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')
我如何建立下拉列表?
How i can build dropdown list?
推荐答案
您需要创建一个构造函数可用,并且在视图中只需将其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.
在Controller中执行以下操作:
In Controller do this:
ViewBag.Organisations = new SelectList(db.Organisations.ToList(),"Id","Organisation");
在SelectList
中的
中,我们需要在最后两个参数中指定的option
标记中指定哪个属性用作value
和哪个属性用作text
.
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.
,然后在View中,您需要以这种方式使用它:
and then in View you would need to use it this way:
@Html.DropDownList("Organization",ViewBag.Organisations as SelectList)
第一个参数将用作select
元素的名称,第二个参数将用于填充select
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
: