2013-09-24 169 views
0

我知道這很簡單,但對於Mvc來說是新的。我希望使用GetDescription方法中的數據 填充下拉框,以便下拉列表顯示說明,並在選擇時將代碼作爲值傳遞。Mvc 3:填充下拉框

我該如何寫html片?

public class HomeController : Controller 
       { 
        public ActionResult Index() 
        { 


         return View(); 
        } 

        public static List<Populate> GetDescription() 
        { 
         List<Populate> myInfor = new List<Populate>() 
         { 
          new Populate{Id=1,Description="Lagos", Code="lag"}, 
          new Populate{Id=2,Description="Ibadan", Code="lba"}, 
          new Populate{Id=3,Description="Akure", Code="Aku"}, 
          new Populate{Id=4,Description="Ejigbo", Code="Eji"}, 
          new Populate{Id=5,Description="Oshogbo", Code="Osh"} 
         }; 

         return myInfor; 
        } 

       } 


       public class Populate 
       { 
        public int Id { get; set; } 
        public string Description { get; set; } 
        public string Code { get; set; } 
       } 


       Here is the html 
       ********************* 

       @model PopulateDropDownList.Models.Populate 

       @{ 
        ViewBag.Title = "Index"; 
       } 

       <h2>Index</h2> 



       <p> 


       @Html.DropDownList(Model.id, Model.Description, "--Select One--") 

       </p> 

回答

2

你也可以那樣做。

修改了一下你的代碼:

public static class Helper 
{ 
       public static List<SelectListItem> GetDescription() 
       { 
        List<Populate> myInfor = new List<Populate>() 
        { 
         new Populate{Id=1,Description="Lagos", Code="lag"}, 
         new Populate{Id=2,Description="Ibadan", Code="lba"}, 
         new Populate{Id=3,Description="Akure", Code="Aku"}, 
         new Populate{Id=4,Description="Ejigbo", Code="Eji"}, 
         new Populate{Id=5,Description="Oshogbo", Code="Osh"} 
        }; 

        var result = new List<SelectListItem>(); 
         var items = from n in myInfor 
          select new SelectListItem 
          { 
           Text = n.Description, 
           Value = n.Id.toString() 
          }; 
       foreach (var item in items) 
        result.Add(item); 

        return result; 
       } 
} 

不是在您查看: @using YourProject.Helper

@Html.DropDownList("AnyTextAsID", Helper.GetDescription()) 
+0

這就是我所得到的。 CS0103:名稱'GetDescription'在當前上下文中不存在。 – user2320476

+0

@ user2320476我編輯了我的答案。將此代碼包含在靜態類中並在類級別上調用它​​。 –

0

你可以在你看來這樣做:

@{ 
    Dictionary<string, string> populate = new Dictionary<string, string>(); 
     populate.Add("Lagos", "lag"); 
     populate.Add("Ibadan", "lba"); 
     populate.Add("Akure", "aku"); 
     populate.Add("Ejigbo", "eji"); 
     populate.Add("Oshogbo", "osh"); 
} 
@Html.DropDownList("myinfo", new SelectList(populate.ToList(), "Value", "Key", "Lagos"), new { id = "Populate" }) 
+0

感謝。這不起作用。 CS0117:'PopulateDropDownList.Models.Populate'不包含'ToList'的定義 – user2320476