2013-02-20 56 views
2

我有一個需要州和國家選擇的註冊頁面。填充這些下拉列表的項目來自外部數據庫。如何爲DropdownList加載列表

如何在頁面呈現之前調用這些列表來填充這些列表?

public class RegisterModel 
{ 
... 
public IEnumerable<SelectListItem> States {get;set;} 
public IEnumerable<SelectListItem> Countries {get;set;} 
... 
} 

//Register.cshtml 
@model Adw.Web.Models.RegisterModel 

@Html.LabelFor(m => m.State) 
@Html.DropDownListFor(m =>m.State, new SelectList(Model.States)) 

//Controller 
public ActionResult Register() 
    { 
     ..... 
     RegisterModel rm = new RegisterModel(); 

     //The factories return List<string> 
     rm.States = new SelectList(stateFactory.Create(states.Payload)); 
     rm.Countries = new SelectList(countryFactory.Create(country.Payload)); 

     return View(rm); 
    } 

通過以上的設置,我收到:

有型「的IEnumerable」具有關鍵的「國」無ViewData的項目。

總結 - 我需要做一個web服務調用,以在頁面呈現之前獲取2個下拉列表的數據。

+0

我最近回答了這樣的問題,也許那裏的信息會幫助你。 http://stackoverflow.com/questions/14714923/set-a-default-value-for-a-dropdownlist-from-a-list-coming-from-another-controlle/14715206#14715206 – mmeasor 2013-02-20 21:56:57

+0

我試圖設置它正如您的鏈接中所建議的那樣,但仍似乎無法使其發揮作用。我已更新我的帖子以反映這些更改。 – Zholen 2013-02-21 05:27:20

回答

2

試試這個

型號:

public class RegisterModel 
{ 
    ... 
    public IList<string> States { get; set; } 
    public IList<string> Countries { get; set; } 
    .... 
} 

控制器:

RegisterModel rm = new RegisterModel(); 

// read data from the database and add to the list 
rm.States = new List<string> { "NY", "LA" }; 
rm.Countries = new List<string> { "USA", "Canada" }; 

的觀點:

@Html.LabelFor(x=>x.Countries) 
@Html.DropDownListFor(x=>x.Countries, new SelectList(Model.Countries)) 

@Html.LabelFor(x=>x.States) 
@Html.DropDownListFor(x=>x.States, new SelectList(Model.States)) 

希望這會工作。

+0

好極了!非常感謝,我不知道爲什麼這對我來說似乎很難。儘管如此,我的用戶準備好提交表單後,如何檢索選定的值?我還有另外兩個名爲State和Country的字符串屬性,我試圖填充,但也許我不需要? – Zholen 2013-02-21 16:12:42

+1

致@Zholen。您可以在methods參數中使用「FormCollection集合」。請參閱以下鏈接[鏈接](http://stackoverflow.com/questions/15007068/mvc-4-how-to-get-the-selected-item-from-a-dropdown-list)。 – Murtoza 2013-02-21 16:38:24