DropDownList from IEnumerable [closed]

2019-01-12 13:18发布

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.

1条回答
劳资没心,怎么记你
2楼-- · 2019-01-12 13:47

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();
查看更多
登录 后发表回答