Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc dropdown list using ViewBag

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?

like image 756
I.Bond Avatar asked Sep 21 '17 10:09

I.Bond


1 Answers

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.

@model BCO.Models.SelectOrganisationViewModel

@{
    ViewBag.Title = "OrganisationInfo";
}

<div>
    @Html.DropDownListFor(o => o.OrganisationId,
        new SelectList(ViewBag.Organisations, "Id", "Name"))
</div>

The SelectList itself expects

  • the list to fill the DropDownList with
  • the value ("Id")
  • the text ("Name")

as parameters.

like image 127
Valentin Sky Avatar answered Oct 05 '22 12:10

Valentin Sky