2013-05-02 72 views
0

我只是在學習MVC。這是我迄今爲止嘗試:列表沒有顯示在DropDown菜單在查看

public class StoreXml 
{ 
    public string StoreCode { get; set; } 


    public static IQueryable<StoreXml> GetStores() 
    { 
     return new List<StoreXml> 
     { 
      new StoreXml { StoreCode = "0991"}, 
      new StoreXml { StoreCode = "0015"}, 
      new StoreXml { StoreCode = "0018"} 
     }.AsQueryable(); 
    } 

在控制器:

public SelectList GetStoreSelectList() 
    { 
     var Store = StoreXml.GetStores(); 
     return new SelectList(Store.ToArray(),"StoreCode"); 
    } 

    public ActionResult IndexDDL() 
    { 
     ViewBag.Store = GetStoreSelectList(); 
     return View(); 
    } 

在View:

@Html.DropDownList("store", ViewBag.Stores as SelectList, "Select a Store") 

什麼我錯在這裏做什麼?下拉菜單僅顯示Cie_Mvc.Models.StoreXml,但沒有值。請建議。

回答

0

你將它存儲在ViewBag.Store,把它在ViewViewBag.Stores

public ActionResult IndexDDL() 
{ 
    ViewBag.Stores = GetStoreSelectList(); 
    return View(); 
} 

@Html.DropDownList("store", ViewBag.Stores as SelectList, "Select a Store") 

作爲一個方面說明,這是與使用dynamicobject問題。我建議將該物業放在ViewModel,以便獲得智能感知。

+0

謝謝加布,我用ViewBag.Stores這兩種情況。還是一樣的。 – prasuangelo 2013-05-03 14:06:25

0

我會做不同的。我會從我的類,如清單分開我的課:

public class StoreXml 
{ 
    public string StoreCode { get; set; } 
} 

然後我會使用的東西就像一個倉庫,以獲得一些數據,即使是硬編碼,或者你可以填充從你的控制器列表。始終使用視圖模型來表示對視圖數據:

public class MyViewModel 
{ 
    public string StoreXmlCode { get; set; } 

    public IEnumerable<StoreXml> Stores { get; set; } 
} 

然後控制器可以是這個樣子:

public class MyController 
{ 
    public ActionResult MyActionMethod() 
    { 
      MyViewModel viewModel = new MyViewModel(); 

      viewModel.Stores = GetStores(); 

      return View(viewModel); 
    } 

    private List<StoreXml> GetStores() 
    { 
      List<StoreXml> stores = new List<StoreXml>(); 

      stores.Add(new StoreXml { StoreCode = "0991"}); 
      stores.Add(new StoreXml { StoreCode = "0015"}); 
      stores.Add(new StoreXml { StoreCode = "0018"}); 

      return stores; 
    } 
} 

然後你的看法可能是這個樣子:

@model MyProject.ViewModels.Stores.MyViewModel 

@Html.DropDownListFor(
    x => x.StoreXmlCode, 
    new SelectList(Model.Stores, "StoreCode", "StoreCode", Model.StoreXmlCode), 
    "-- Select --" 
) 

我希望這可以引導你在正確的方向:)