简体   繁体   中英

Drop-down List in MVC 3

After looking at many examples of drop-down menus, here's my situation.

I have a database table: Companies

In my registration view model, I have the following: public int? CompanyId { get; set; } public int? CompanyId { get; set; } public int? CompanyId { get; set; } (thought about changing this to public IEnumerable<Company> Companies { get; set; } )

In my registration view, the user can select which company he works for. I would like to have a drop-down list of what companies are in our database for the user to select from.

I have a company repository set up to get all companies and return as an IEnumerable .

How do I approach this? Would I be better off doing this in the view model or the controller?

In your model, declare two properties.

public int? CompanyId { get; set; }
public IEnumerable<SelectListItem> Companies { get; set; }

Then in your view

@Html.LabelFor(x => x.CompanyId)
@Html.DropDownListFor(x => x.CompanyId, Model.Companies)

This will create a select list that will set your CompanyId property and use the Companies as the option values.

You can create the SelectList easily enough. I'm guessing it would be something like

Companies.AddRange(
  aListOfCompanies.Select(x => 
    new SelectListItem { Text = x.CompanyName, Value = x.CompanyId.ToString() }));

Create a method in your ViewModel like(GetCompanies()) then in your Controller make a SelectList object with what it return your viewModel object. then you can pass it to the view by viewBag or a property in your model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM