来自 IEnumerable 的 DropDownList [英] DropDownList from IEnumerable

查看:22
本文介绍了来自 IEnumerable 的 DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想要一个由 IEnumerable 填充的简单下拉列表.我有

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

@model WebApplication4.Models.VENDOR

该模型包含一个 IEnumerable 的 BANK 对象.我希望下拉列表由这些对象的字段 BANK_NAME 填充.我是 MVC 和 .NET 的新手.这似乎是一项简单的任务,我只是不知道该怎么做.

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.

推荐答案

使用特定于您的视图的视图模型,

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;}
}

在你的 GET Action 方法中

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);
}

并且在您的视图中,它是强类型到 CreateVendor 视图模型的,您可以使用 DropDownListFor 辅助方法.

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" />    
}

而您的 HttpPost 操作方法将是

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
}

如果您想用表格中的数据替换硬编码的 Banks 数据.将类/属性名称替换为您的实际类/属性名称.

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();

这篇关于来自 IEnumerable 的 DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆