我正在创建一个ASP.NET Web应用程序作为我学习的一部分。
目前我正在创建添加产品部分。我已将一些图像添加到图像文件夹中,并希望将这些图像名称添加到下拉列表中。这是我的教程提供的代码:
编辑:如下所述,不再推荐使用ArrayList。这是我尝试使用此方法的部分原因。 public void GetImages()
{
try
{
//get all filepaths
string[] images = Directory.GetFiles(Server.MapPath("~/Images/Products/"));
//get all filenames and add them to an arraylist.
ArrayList imagelist = new ArrayList();
foreach (string image in images)
{
string imagename = image.Substring(image.LastIndexOf(@"\", StringComparison.Ordinal) + 1);
imagelist.Add(imagename);
}
//Set the arrayList as the dropdownview's datasource and refresh
ddlImage.DataSource = imageList;
ddlImage.AppendDataBoundItems = true;
ddlImage.DataBind();
}
然后在页面加载时使用它。
当我使用网络表单创建它时,这很好用。但是,我想对此项目使用@Html.DropDownList
操作链接。使用scaffolding连接数据库时,会创建并填充这些下拉列表,我可以看到为视图生成 SelectList 的位置,即:
// GET: Products/Create
public ActionResult Create()
{
ViewBag.TypeId = new SelectList(db.ProductTypes, "Id", "Name");
return View();
}
我只是不确定如何将我的教程示例转换为SelecList初始化程序所要求的IEnumerable。我得到的最接近的是:
List<SelectListItem> imagelist = new List<SelectListItem>();
foreach (string image in images)
{
string imagename = image.Substring(image.LastIndexOf(@"\", StringComparison.Ordinal) + 1);
imagelist.Add(new SelectListItem() { Text = imagename });
}
IEnumerable<string> imager = imagelist as IEnumerable<string>;
但这似乎不对。
编辑:如下所述,我需要将值添加到新的SelectListItem
:
imagelist.Add(new SelectListItem() { Text = imagename, Value = "Id" });
这似乎更好。虽然我不确定是否需要创建“imager”,但imageList为IEnumerable。 SelectList是不是已经可枚举?
增加的问题:
另外,我应该如何将这个新列表添加到ViewBag
?:
ViewBag.TypeId = new SelectList(db.ProductTypes, "Id", "Name");
ViewBag.TypeId = new SelectList()
return View();
我目前的问题是它在GetImages
方法范围内,我不确定如何访问它。我认为答案是超级基本的,但我对此很新。
任何建议都将不胜感激!
再次感谢。
答案 0 :(得分:0)
//Create a new select list. the variable Imagelist will take on whatever type SelectList.
var Imagelist = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = imagename, Value = "Id"},
new SelectListItem { Text = imagename2, Value = "Id2"},
}, "Value" , "Text");
//You can now use this viewbag in your view however you want.
ViewBag.Image = Imagelist.