DropDownList的自IEnumerable [英] DropDownList from IEnumerable
问题描述
我只想将由一个IEnumerable填充一个简单的下拉列表中。我有
I just want a simple drop down list that will be populated by an IEnumerable. I have
@model WebApplication4.Models.VENDOR
该模型包含BANK对象的IEnumerable。我想的下拉菜单,这些对象的字段,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
helper方法
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
}
如果您要更换硬盘$ C $光盘从表中的数据银行
数据。与你的实际的类/属性名称更换类/属性名称。
If you want to replace the hardcoded Banks
data 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();
这篇关于DropDownList的自IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!