My table in db have fields : Id
,Organisation
,Info
.
I want make dropdowm list like that:
<select>
<option value='Id there'>'Organisation there'</option>...
I'm try to do it, using ViewBag:
ViewBag.Organisations = db.Organisations.ToList(); // get all fields from table using dbContext
and in View:
@Html.DropDownList('I don`t know what i shoud write here, please help')
How i can build dropdown list?
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.In Controller do this:
in
SelectList
we need to specify which property to use asvalue
and which to use astext
in theoption
tag which we are specifying in last two parameters.and then in View you would need to use it this way:
Here first parameter would be used as name of
select
element and second one will be used to populate theoption
elements in theselect
Following is the list of overloads available for
Html.DropDownList
:https://msdn.microsoft.com/en-us/library/system.web.webpages.html.htmlhelper.dropdownlist%28v=vs.111%29.aspx?f=255&MSPPError=-2147217396
You can use selectlist from viewbag as follows
here ViewBag.GetData is populated from the controller, the controller code should be like
I recommend you to define a ViewModel for your page with a
OrganisationId
property. Thus this value will be filled when selecting an entry of the organisations dropdown list.The SelectList itself expects
as parameters.