2016-07-27 41 views
0

我正在創建一個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方法中,而且我不確定如何訪問它。我認爲答案是超級基礎,但我對此很新。

任何意見將不勝感激!

再次感謝。

+2

不要再使用ArrayList,句點。爲什麼代碼看起來不對?您必須在SelectListItem中設置一個值。 – CodeCaster

+0

而不是'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

+0

好吧,我到了那裏。我明白設定價值。現在我只需要將它添加到ViewBag中。我會如何寫它? ViewBag.Image = new SelectList(?) – ScottCoding

回答

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. 
相關問題