DropDownList from IEnumerable

I just want a simple drop down list that will be populated by an IEnumerable. I have

@model WebApplication4.Models.VENDOR

The model contains an IEnumerable of BANK objects. I want the dropdown to be populated by a field of these objects, BANK_NAME. I’m new to MVC and .NET. This seems like an easy task, I just don’t know how to do it.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Using a viewmodel which is specific to your view,

public class CreateVendor
{ 
  public string VendorName {set;get;}
  public List<SelectListItem> Banks {set;get;}
  public int SelectedBank {set;get;}
}

And in your GET Action method

public ActionResult Create()
{
  var vm = new CreateVendor();
  //Hard coded for demo. You may replace with your db entries (see below)
  vm.Banks = new List<SelectListItem> {
     new SelectListItem { Value="1","Chase bank" },
     new SelectListItem { Value="2","PNCbank" },
     new SelectListItem { Value="3","BOA" } 
  };
  return View(vm);
}

And in your view, which is strongly typed to the CreateVendor viewmodel, you may use the DropDownListFor helper method.

@model CreateVendor
@using(Html.BeginForm())
{
  <label>Vendor name </label>
  <label>Bank</label>
  @Html.DropDownListFor(s=>s.SelectedBank,Model.Banks,"Select one")
  <input type="submit" />    
}

And your HttpPost action method will be

[HttpPost]
public ActionResult Create(CreateVendor model)
{
  // Read model.VendorName and model.SelectedBank
  //  var vendor = new Models.Vendor();
  //  vendor.Name = model.VendorName;
  //  vendor.BankId= model.SelectedBankId;
  //  yourDbContext.Vendors.Add(vendor);
  //  yourDbContext.SaveChanges();
  //  Redirect to a success action
}

If you want to replace the hardcoded Banksdata with data from your tables. Replace the Class/Property names with your actual class/property names.

  var db= new YourDbContext();
  vm.Banks = db.Banks.Select(s=>  new SelectListItem {
                                        Value=s.BANK_ID.ToString(), 
                                        Text=s.BANK_NAME }).ToList();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x