我正在创建一个ASP.NET Web应用程序作为我的研究的一部分。我可以使用ArrayList作为ASP.NET MVC中的SelectList吗?
目前我正在创建一个添加产品部分。我已经将一些图像添加到图像文件夹,并希望将这些图像名称添加到下拉列表中。这是我的教程提供的代码:
编辑:正如有人指出,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();
}
然后用于页面加载。
当我使用Web窗体创建它时,它工作正常。但是,我想为此项目使用@Html.DropDownList
操作链接。当使用这些dropdownlists创建和填充就好了脚手架连接数据库,我能看到的视图生成的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是不是Enumerable?
问题补充: 另外,我应该怎么添加这个新的列表到ViewBag
:
ViewBag.TypeId = new SelectList(db.ProductTypes, "Id", "Name");
ViewBag.TypeId = new SelectList()
return View();
我当时的问题是,它是GetImages
方法中,而且我不确定如何访问它。我认为答案是超级基础,但我对此很新。
任何意见将不胜感激!
再次感谢。
不要再使用ArrayList,句点。为什么代码看起来不对?您必须在SelectListItem中设置一个值。 – CodeCaster
而不是'string imagename = image.Substring(image.LastIndexOf(@“\”,StringComparison.Ordinal)+ 1)'use'string imagename = Path.GetFileName(image)'(https://msdn.microsoft.com /ru-ru/library/system.io.path.getfilename(v=vs.110).aspx) – feeeper
好吧,我到了那里。我明白设定价值。现在我只需要将它添加到ViewBag中。我会如何写它? ViewBag.Image = new SelectList(?) – ScottCoding