我可以在ASP中使用ArrayList作为SelectList吗.NET MVC
本文关键字:SelectList 作为 NET MVC ArrayList ASP 我可以 | 更新日期: 2023-09-27 17:58:53
我正在创建一个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();
}
然后在页面加载时使用此选项。
当我使用web表单创建它时,这很好。但是,我想在这个项目中使用@Html.DropDownList
操作链接。当使用脚手架连接数据库时,这些下拉列表被创建和填充得很好,我可以看到视图的SelectList是在哪里生成的,即:
// GET: Products/Create
public ActionResult Create()
{
ViewBag.TypeId = new SelectList(db.ProductTypes, "Id", "Name");
return View();
}
我只是不知道如何将我的教程示例转换为IEnumerable,SelecList初始值设定项需要它。我得到的最接近的是:
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
方法中,我不确定如何访问它。我认为答案是非常基本的,但我对此非常陌生。
任何建议都将不胜感激!
再次感谢。
//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.